Local Dev Craft: Scaling a Python Worker with SeaweedFS, RabbitMQ, and KEDA (Part 2)

In part 1 we used kind, KEDA, and LocalStack to run an S3-triggered worker on a laptop. This time we’ll use SeaweedFS for object storage and RabbitMQ for the queue. We’ll upload a file through the S3 API, see what SeaweedFS sends to RabbitMQ, and watch KEDA start a Python worker to pick it up.

When I went back to test part 1, localstack/localstack:latest refused to start without an auth token. Pinning an older image got the demo running again. For the rest of the series I wanted services we could run directly in the cluster, with pinned versions. MinIO was on my list for S3, but its community edition moved to source-only distribution. SeaweedFS ships a container image with an S3 gateway and can publish file changes to RabbitMQ. I also looked at NATS JetStream. I went with RabbitMQ because I wanted to inspect messages in its management UI and configure dead-letter routing when we add retries. LocalStack’s image change and MinIO’s source-only distribution have the details.

The worker switches to Python here. In the next parts we’ll use it for photo processing and eventually run ML models. Today it just logs the file and sleeps for five seconds so we can see the queue drain.

Setting up kind and KEDA

You’ll need Docker, kind, kubectl, Helm, the AWS CLI, and Python 3 with venv. The tested setup used kind 0.33.0 with Kubernetes 1.37.0, KEDA 2.21.1, and a Python 3.13 worker.

Clone the companion repo and run the commands below from part2/. We’ll use a fresh, named cluster so you can leave your part 1 setup in place.

git clone https://github.com/anndev-org/local-dev-craft.git
cd local-dev-craft
git checkout --detach 19840cefb9dbae07d774ca1e1cc2d8aff068f944
cd part2
kind create cluster --name local-dev-craft-part2 --config manifests/kind-config.yaml --wait 120s
kubectl config use-context kind-local-dev-craft-part2
helm repo add kedacore https://kedacore.github.io/charts
helm install keda kedacore/keda --namespace keda --create-namespace --version 2.21.1 --wait

All the Kubernetes resources for the demo go in the default namespace. SeaweedFS and the worker reach RabbitMQ through its Kubernetes Service, rabbitmq.default.svc.cluster.local. If you remember the CoreDNS patch for host.docker.internal on Linux from part 1, we can skip it here.

Setting up RabbitMQ

Let’s start with RabbitMQ, since SeaweedFS needs an exchange to publish to. The RabbitMQ manifest runs one replica of rabbitmq:4.4.1-management. The Service exposes AMQP on port 5672 and the management UI on port 15672. The username and password are demo values for this local cluster.

kubectl apply -f manifests/rabbitmq.yaml
kubectl rollout status deployment/rabbitmq --timeout=180s

In a second terminal, forward both ports and leave the command running.

kubectl port-forward svc/rabbitmq 5672:5672 15672:15672

Open http://localhost:15672 and log in with admin / admin123. We’ll come back here after the first upload.

Declare the exchange before starting SeaweedFS

Now here’s a SeaweedFS gotcha. Its Go CDK publisher expects the RabbitMQ exchange to exist already. Run scripts/setup_queue.py to create the exchange, the queue, and the binding. These are the three calls it makes with pika.

ch.exchange_declare("seaweed-events", exchange_type="fanout", durable=True)
ch.queue_declare("seaweed-events-q", durable=True)
ch.queue_bind("seaweed-events-q", "seaweed-events")
python3 -m venv .venv
.venv/bin/pip install -r scripts/requirements.txt
.venv/bin/python scripts/setup_queue.py

A fanout exchange sends a copy to each queue bound to it. We have one queue today. Later we’ll use the same pattern to give independent processing stages their own copy of an event.

Setting up SeaweedFS

The SeaweedFS manifest runs weed server with the master, volume server, filer, and S3 gateway in one pod. It mounts this configuration at /etc/seaweedfs/notification.toml.

[notification.gocdk_pub_sub]
enabled = true
topic_url = "rabbit://seaweed-events"

topic_url points to the exchange we just created. The container gets the broker address from RABBIT_SERVER_URL. Use the 4.55_full image in the manifest. The _full build includes the Go CDK backend we need for RabbitMQ. I lost a bit of time to the plain image, which ran without publishing any events.

The manifest caps volume files at 64 MB for the demo and stores them in an emptyDir. Replacing the pod gets you an empty store.

kubectl apply -f manifests/seaweedfs.yaml
kubectl rollout status deployment/seaweedfs --timeout=180s

The Deployment can report Ready a few seconds before the S3 gateway starts listening. Run the command below and look for Start Seaweed S3 API Server and port 8333 before forwarding the port. The logs should also show Configure notification message queue for gocdk_pub_sub.

kubectl logs deployment/seaweedfs

In a third terminal, forward the S3 port and leave this command running too.

kubectl port-forward svc/seaweedfs 8333:8333

Use the first terminal to create the bucket. The AWS CLI expects credentials and a region. The S3 gateway in this setup accepts the demo values below. If the port forward exits on the first request, restart it once the gateway is listening and try again.

export AWS_ACCESS_KEY_ID=any AWS_SECRET_ACCESS_KEY=any AWS_DEFAULT_REGION=us-east-1
aws --endpoint-url=http://localhost:8333 s3api create-bucket --bucket photos

What lands in the queue?

You can use one of your own photos. I’ll use the PNG already in the repo so you can run the commands as they are.

aws --endpoint-url=http://localhost:8333 s3 cp images/rabbitmq-get-messages.png \
  s3://photos/uploads/sample-0.png

In RabbitMQ’s management UI, go to Queues and Streams, open seaweed-events-q, and expand Get messages. Set Ack Mode to Nack message requeue true and request 7 messages. That puts them back for the worker to read later. RabbitMQ HTTP API reference

On a fresh setup we get five messages from creating the bucket and initializing SeaweedFS’s internal paths, one from creating the uploads/ directory, and one for the file itself. In my first run I used IMG_0001.jpg. You can see the directory and file events at the end of the list.

RabbitMQ shows separate events for the uploads directory and IMG_0001.jpg, each with a key header and base64 payload.

The filer publishes changes across all buckets. The AMQP key header gives us the full filer path, so we can start by filtering on /buckets/photos/. The message body is a protobuf filer_pb.EventNotification. That’s the base64 payload in the screenshot. Once we decode it, we can tell a file update from a directory change or deletion.

The Python worker

The worker reads the header and passes the path and the body to handle(). Here’s the part that decides what to process.

def handle(path: str, body: bytes) -> None:
    if not path.startswith(PREFIX):
        print(f"Skipping {path}: not in bucket {BUCKET}")
        return

    event = filer_pb2.EventNotification()
    event.ParseFromString(body)

    if not event.HasField("new_entry"):
        print(f"Skipping {path}: deleted")
        return
    entry = event.new_entry
    if entry.is_directory:
        print(f"Skipping {path}: a folder")
        return

    key = path[len(PREFIX):]
    action = "Changed" if event.HasField("old_entry") else "New"
    print(f"{action} file: {BUCKET}/{key} "
          f"({entry.attributes.file_size} bytes, {entry.attributes.mime or 'unknown type'})")
    time.sleep(WORK_SECONDS)

The callback acknowledges skipped events as well as processed ones. It also logs and acknowledges exceptions from handle(), so those failed events are discarded. We’ll add retries and dead-letter queues when the worker has real work to retry.

The worker sets prefetch_count=1. RabbitMQ can give each consumer one unacknowledged message at a time, which leaves work for the pods KEDA adds later. With pika.Connection in pika 1.5.0, the I/O runs on a background thread, so the five-second sleep in the callback leaves heartbeats running. Pika FAQ

One more container gotcha. My first worker ran as PID 1 without a SIGTERM handler, so Kubernetes had to wait out the 30-second grace period and kill it. Now the handler wakes the main thread, which closes the Pika connection. Pika cancels the consumer and gives pending callbacks time to finish. Its default close timeout is 10 seconds, which gives our five-second callback time to acknowledge the message. With longer work, the connection can close before the callback acknowledges it, and RabbitMQ can deliver the message again. Pika connection shutdown

The Dockerfile uses grpcio-tools==1.85.0 to generate filer_pb2.py from SeaweedFS 4.55’s filer.proto in the first build stage. The runtime image uses Python 3.13.13 with pika==1.5.0 and protobuf==7.36.2. Build it and load it into kind.

docker build -t photo-worker:v1 worker/
kind load docker-image photo-worker:v1 --name local-dev-craft-part2

Wiring the worker to KEDA

The worker manifest starts the Deployment at zero replicas and uses imagePullPolicy: IfNotPresent so the pods can run the image we just loaded. It has one Secret for the AMQP connection string. The worker reads that Secret directly and KEDA gets it via a TriggerAuthentication. Here’s the ScaledObject.

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: photo-worker-scaler
  namespace: default
spec:
  scaleTargetRef:
    name: photo-worker
  minReplicaCount: 0
  maxReplicaCount: 3
  pollingInterval: 10
  cooldownPeriod: 30
  triggers:
    - type: rabbitmq
      metadata:
        protocol: amqp
        queueName: seaweed-events-q
        mode: QueueLength
        value: "2"
      authenticationRef:
        name: rabbitmq-conn-auth

With the AMQP protocol, the scaler counts messages that are ready for delivery. value: "2" targets two ready messages per replica, up to three replicas. At zero replicas KEDA checks for work every 10 seconds. The 30-second cooldown to go back to zero runs from when KEDA last saw the trigger active. RabbitMQ scaler and ScaledObject reference

Start the watch in a separate terminal before applying the manifest, so you can see the worker appear.

kubectl get pods -l app=photo-worker -w
kubectl apply -f manifests/worker.yaml

The messages from the first upload are still waiting. Check the logs while the worker is running. You should see it skip the housekeeping events and log New file: photos/uploads/sample-0.png.

kubectl logs -l app=photo-worker --prefix --tail=-1

Try a burst of uploads

Wait for the worker pods to disappear, then upload six files with distinct keys. We can reuse the same PNG since the worker reads the event and logs its metadata.

for n in 1 2 3 4 5 6; do
  aws --endpoint-url=http://localhost:8333 s3 cp images/rabbitmq-get-messages.png \
    "s3://photos/uploads/sample-$n.png"
done

This time the bucket and directory already exist, so the six uploads give us six file events. In my test with six JPEGs, the Deployment reached three pods about ten seconds after the first upload. The files were done at about twenty seconds, and the Deployment went back to zero at around forty to forty-five seconds. Your peak and timing depend on how many messages are still waiting when the autoscaler samples the queue.

When you’re done, stop the watches and port forwards with Ctrl+C and delete the demo cluster.

kind delete cluster --name local-dev-craft-part2

Where the storage events fall short

The filer tells us which path changed. It also tells us about its own directories, and the worker needs SeaweedFS’s protobuf schema to make sense of those changes. There’s another detail in RabbitMQ. The exchange and queue are durable, but the notifications in this setup are published as transient messages. A broker restart can lose queued work.

For the photo pipeline I want the app to say that a photo was stored and include its ID and object key. In part 3 we’ll upload the object, then commit the photo’s metadata and an outbox row together in the database. A relay will publish the event from the outbox, and the thumbnail and metadata workers will each get a copy on their own queue.

Categories: local-dev