$ cat job-board-api/part-25.md
Building a Job Board API, Part 25: One Queue Interface, Two Clouds

I’m sharing one of my projects here from the beginning, step by step. It’s a Job Board API built with Django, Django REST Framework, PostgreSQL and Docker Compose, with S3 and SQS (through LocalStack), Redis, and a background worker.
I’m a junior engineer looking for my first role in DevOps, SRE or Cloud. That’s why I build projects like this and write about them in public. It shows how I think, and writing it down helps me really understand it.
In Part 24, I ran Azure Service Bus locally and learned how it behaves. Now I write the code. Earlier in this project, I put the queue behind a small interface, Queue, with four methods: send, receive, delete and ping. The publisher, the worker and the readiness check only use those four. So in this part I add a second implementation, ServiceBusQueue, next to SQSQueue, and get_queue() picks one by CLOUD_PROVIDER. The interface didn’t change, so the publisher, the worker and their tests didn’t change either. The hard part was inside the class, and mostly in one method: ping(), which could hang forever on a frozen broker.
QUEUE_ERRORS: catching errors from either cloud
# Errors a caller should treat as "the queue is unavailable right now", on either cloud.
QUEUE_ERRORS = (BotoCoreError, ClientError, AzureError)
- except accepts a tuple of exception classes and catches any of them.
- Before, the publisher and the worker imported BotoCoreError, ClientError themselves. On Azure, a Service Bus error would have escaped their except clauses. In the worker, the loop would have crashed instead of logging and retrying. In the publisher, the error would have reached Django’s on_commit callback.
- After, the module that knows both clouds, cloud/queue.py, defines what “queue unavailable” means. Callers just catch QUEUE_ERRORS.
- AzureError is the base class of every Azure SDK error, including all the ServiceBus*Errors. Catching the base class means a new error type in a future SDK version is still caught.
In the publisher and the worker, two sed commands did the change:
sed -i 's/^from botocore.exceptions import BotoCoreError, ClientError\(.*\)$/from cloud.queue import QUEUE_ERRORS\1/' jobs/events.py worker/run_worker.py
sed -i 's/except (BotoCoreError, ClientError):/except QUEUE_ERRORS:/' jobs/events.py worker/run_worker.py
\(.*\) and \1 are a sed capture group: they save whatever followed the old import (the worker has a # noqa: E402 comment there) and put it back after the new one. The worker’s except Exception around handling a message didn’t change, because a handler failure isn’t a queue error. The tests didn’t change either. The fake queue from Part 20 raises botocore’s EndpointConnectionError, which is still in the tuple.
ServiceBusQueue, method by method
The constructor
class ServiceBusQueue(Queue):
"""Azure Service Bus queue, peek-lock mode.
The SDK's clients are not thread-safe. The API only sends (under a lock);
the worker only receives and deletes, from one thread.
"""
def __init__(self, connection_string: str, queue_name: str):
self.name = queue_name
self._connection_string = connection_string
parts = dict(p.split("=", 1) for p in connection_string.split(";") if p)
self.url = f"{parts['Endpoint'].rstrip('/')}/{queue_name}" # no key in it: safe to log
self._client = ServiceBusClient.from_connection_string(
connection_string, retry_total=3, try_timeout=5
)
self._send_lock = threading.Lock()
self._ping_lock = threading.Lock()
self._sender = None
self._receiver = None
self._pending = {}
- The docstring records the threading rule, because nothing in the code enforces it. The SDK’s README says its clients aren’t guaranteed to be thread-safe and recommends a threading.Lock(). That matters here: gunicorn runs with threads (Part 17), so several requests can publish at the same time through the one cached queue object. boto3 clients are thread-safe, so SQSQueue never needed this.
- Parsing the connection string: split(“;”) gives pieces like Endpoint=sb://servicebus, and if p skips the empty piece after the last ;. split(“=”, 1) splits only at the first =, because keys often end with = (base64 padding). A plain split(“=”) would break them.
- self.url is sb://servicebus/job-board-status. The worker logs it at startup (Worker started, queue <url>), so it must not contain the key. Building it from Endpoint alone guarantees that.
- No network call here. from_connection_string only stores settings, and connections open on first use. That’s a lesson from Part 13: a constructor that connects can hang whatever creates the object.
- retry_total=3 looks like SQS’s total_max_attempts: 3, but they count differently. SQS counts all attempts (3). Service Bus counts retries (3 more after the first).
- try_timeout=5 limits each attempt of an operation. But it does not cover one important step, as ping() will show.
- _sender and _receiver start as None and are created on first use, then reused. An AMQP link stays open.
- _pending is the bridge between receive() and delete(). More on it below.
send (the version from this part)
def send(self, body: dict) -> str:
message_id = str(uuid.uuid4())
message = ServiceBusMessage(json.dumps(body), message_id=message_id)
with self._send_lock:
try:
if self._sender is None:
self._sender = self._client.get_queue_sender(self.name)
self._sender.send_messages(message)
except AzureError:
self._sender = self._discard(self._sender)
raise
return message_id
- I choose the message ID. SQS creates the MessageId on the server and returns it. Service Bus lets the sender set message_id, and doesn’t return one. A UUID I create is never None, so the publisher’s log line always has an ID. This one line turns out to matter a lot in Part 26.
- with self._send_lock: only one thread at a time creates or uses the shared sender. A send takes milliseconds, so other request threads wait briefly.
- On any Azure error: throw away the sender, because it may be broken, then raise the same error again. The next send opens a fresh link. Without this, one broken link could make every later publish fail until the process restarts. This method changed again in Part 26, after the real API showed what a broker outage does to a user’s request.
receive and _pending
def receive(self, max_messages: int = 10, wait_seconds: int = 20) -> list[QueueMessage]:
try:
if self._receiver is None:
self._receiver = self._client.get_queue_receiver(self.name)
received = self._receiver.receive_messages(
max_message_count=max_messages, max_wait_time=wait_seconds
)
except AzureError:
self._receiver = self._discard(self._receiver)
raise
self._pending = {str(m.lock_token): m for m in received}
return [
QueueMessage(
id=str(m.message_id or m.sequence_number),
body=json.loads(str(m)),
receipt_handle=token,
)
for token, m in self._pending.items()
]
- The same signature and defaults as SQS (10 messages, 20-second long poll), so the worker calls it the same way.
- _pending maps each lock token to the SDK’s message. A lock token identifies one delivery, and a message gets a new token every time it’s delivered.
- The map is replaced on every receive, not added to. Messages the worker failed to handle are simply dropped from the map. Their locks expire, and Service Bus delivers them again with new tokens, so the old entries would be useless anyway. If I added to the map instead, it would grow with every failed message.
- receipt_handle=token: I reuse SQS’s field name for the lock token. To the worker, both mean “the thing delete needs”. That’s why QueueMessage didn’t need to change.
- m.message_id or m.sequence_number: my sends always set message_id, but a message sent by another tool might not. The broker’s sequence number is always set, so the ID is never the text “None”.
delete
def delete(self, message: QueueMessage) -> None:
received = self._pending.pop(message.receipt_handle, None)
if received is None or self._receiver is None:
raise ServiceBusError(f"No lock held for message {message.id}; it will be redelivered")
self._receiver.complete_message(received)
This is the part that follows directly from Part 24: complete_message must run on the receiver that holds the lock, so delete finds the SDK message in _pending and completes it on self._receiver.

When there’s no entry, for example because the receiver was replaced after an error, delete raises a ServiceBusError, not a KeyError. That difference matters: ServiceBusError is in QUEUE_ERRORS, so the worker logs Could not delete message …; it will be redelivered and carries on. A KeyError would escape the worker’s except and crash it. The message comes back after its lock expires, and the worker’s idempotency from Part 12 makes that harmless.
ping(): the health check that could hang forever
ping() is what /readyz calls to check the queue (Part 13). It must answer quickly, whatever state the broker is in. The final version looks over-engineered at first, so here’s how I got there.
Version 1 failed a healthy broker
The first ping() opened a receiver and peeked, with try_timeout=1 and a peek timeout=1. Against a healthy emulator, it failed after 1004 ms with ServiceBusError: Message peek failed … please retry. Instead of guessing, I measured every combination of the two limits:
- try_timeout 1, peek 1: failed, 1004 ms
- no try_timeout, peek 1: failed, 1002 ms
- try_timeout 1, peek 5: failed, 1005 ms
- no try_timeout, peek 5: ok, 1002 ms
- try_timeout 3, peek 3: ok, 1004 ms
Every run took about 1 second, pass or fail, and any 1-second limit failed. So the operation itself takes about 1 second on the emulator, and my limit was simply too small. And just opening a receiver also took about 1 second, so the peek added nothing. I dropped it.
Version 2 hung forever on a frozen broker
In Part 13, I learned that a stopped dependency and a frozen one are different failures. Stopped means gone: the name doesn’t resolve, and calls fail fast. Frozen (docker compose pause) means the kernel still accepts the TCP connection, but nothing ever answers. With a frozen broker, ping() never returned. The process ran until my timeout 30 killed it (exit=124). try_timeout was set, so why didn’t it help? To find out where it hung, I used faulthandler, from Python’s standard library:
faulthandler.dump_traceback_later(15, exit=True, file=sys.stdout)
It sets a timer: if the process is still running after 15 seconds, it prints every thread’s stack and exits. It’s the quickest way to find where a hang is, without a debugger. The stack, read from the bottom up:
_pyamqp/_transport.py, line 561 in _read
_pyamqp/_transport.py, line 360 in read
_pyamqp/_transport.py, line 418 in receive_frame
_pyamqp/sasl.py, line 66 in _negotiate
_pyamqp/sasl.py, line 115 in negotiate
_pyamqp/_connection.py, line 238 in _connect
...
_servicebus_receiver.py, line 234 in __enter__
/app/cloud/queue.py, line 170 in ping
My ping, then opening the receiver, then the connection’s _connect, then SASL negotiation, which is the AMQP login step, and finally a socket read that never returns. The SDK has no time limit on the AMQP login. try_timeout covers operations and link opens, but not that step. So with a frozen broker, a fresh connection can hang however I configure the SDK.
Version 3: a deadline the SDK can’t take away
PING_SECONDS = 2
def ping(self) -> None:
# The SDK has no limit on the AMQP login (SASL) step: a frozen broker hangs it.
# So the check runs in a thread and we wait at most PING_SECONDS for it.
# One ping at a time: while an old one is stuck, fail fast instead of piling up threads.
if not self._ping_lock.acquire(blocking=False):
raise ServiceBusError("Previous ping still running; the broker is not answering")
outcome = {}
def attempt():
try:
with ServiceBusClient.from_connection_string(
self._connection_string, retry_total=0, try_timeout=self.PING_SECONDS
) as client, client.get_queue_receiver(self.name):
pass # opening = connect + login + attach to the queue
except Exception as exc:
outcome["error"] = exc
finally:
self._ping_lock.release()
thread = threading.Thread(target=attempt, name="servicebus-ping", daemon=True)
thread.start()
thread.join(self.PING_SECONDS)
if thread.is_alive():
raise ServiceBusError(f"Ping timed out after {self.PING_SECONDS} s")
if "error" in outcome:
raise outcome["error"]
Piece by piece:
- PING_SECONDS = 2. A healthy ping took 1003 to 1014 ms, so 2 seconds is about twice that. It’s a class attribute, so a test can change it on one object.
- The check runs in a thread, and join(2) waits at most 2 seconds. If the thread is still alive after that, the attempt is stuck. I raise a timeout error and leave the thread behind. Python can’t kill a thread. It ends by itself when the socket finally errors or the broker answers.
- daemon=True: Python doesn’t wait for daemon threads when the process exits, so a stuck ping never blocks gunicorn from restarting a worker process.
- name=”servicebus-ping” shows up in thread dumps, so a stuck thread is easy to identify.
- Opening the receiver is the whole check. Entering the with block connects, logs in and attaches a link to the queue. That proves the broker answers, the key works, and the queue name is known. Then the block closes it.
- Its own client, created and closed per ping. It never touches the shared _client, _sender or _receiver, so it’s thread-safe without sharing a lock with send.
- retry_total=0: one try, no retries. A health check should report the first failure, quickly.
- outcome = {}: a thread can’t return a value to the code that started it. So the thread writes its exception into this dict, and ping() re-raises it, so /readyz reports the real error type.
Single-flight: one stuck thread at most
The lock line at the top is the last piece:
if not self._ping_lock.acquire(blocking=False):
raise ServiceBusError("Previous ping still running; the broker is not answering")
acquire(blocking=False) takes the lock if it’s free. If another ping holds it, it returns False at once, without waiting. So while one stuck thread is still waiting on a frozen broker, every new ping fails in about 0 ms, without starting another thread. Without this, every readiness check during a freeze would leave one more stuck thread with an open socket. The thread releases the lock in its finally, which can be much later, after the broker unfreezes. That’s why it’s a plain threading.Lock: it can be released by a different thread than the one that acquired it. An RLock couldn’t do that. Why not just set a socket timeout? The hang is inside the SDK’s own private SASL read, and no SDK setting reaches it. Editing a private SDK socket would break on the next SDK release. A thread with a deadline only uses the SDK’s public API.
get_queue(): the only place that picks the cloud
@lru_cache(maxsize=1)
def get_queue() -> Queue:
if settings.CLOUD_PROVIDER == "azure":
return ServiceBusQueue(
settings.SERVICE_BUS_CONNECTION_STRING, settings.SERVICE_BUS_QUEUE_NAME
)
return SQSQueue(settings.SQS_QUEUE_NAME)
- @lru_cache(maxsize=1): one queue object per process. For Service Bus, that means one AMQP connection and its links, reused. That’s exactly what the SDK is designed for.
- The return type is Queue, the interface, not either class, so callers can’t start depending on SQS-only or Service-Bus-only attributes.
Each cloud loads only its own settings
In Part 23, the SQS settings stayed above the if CLOUD_PROVIDER branch, “until Step 2”. So even CLOUD_PROVIDER=azure required AWS_REGION and SQS_QUEUE_NAME. An Azure deployment would have needed fake AWS values just to start. Now they move inside the AWS branch:
if CLOUD_PROVIDER == "aws":
AWS_REGION = env("AWS_REGION")
# Queue: SQS
AWS_SQS_ENDPOINT_URL = env("AWS_SQS_ENDPOINT_URL", "") or None
SQS_QUEUE_NAME = env("SQS_QUEUE_NAME")
# Storage: S3
AWS_STORAGE_BUCKET_NAME = env("AWS_STORAGE_BUCKET_NAME")
...
else:
# Queue: Service Bus
SERVICE_BUS_CONNECTION_STRING = env("SERVICE_BUS_CONNECTION_STRING")
SERVICE_BUS_QUEUE_NAME = env("SERVICE_BUS_QUEUE_NAME")
# Storage: Blob
AZURE_ACCOUNT_NAME = env("AZURE_ACCOUNT_NAME")
...
- AWS_REGION comes first, because both SQS and S3 use it.
- Two Service Bus settings, both required: the connection string covers the endpoint and the credential, and the queue name is separate because one namespace can hold many queues.
In .env.example:
# Azure Service Bus (used when CLOUD_PROVIDER=azure). The emulator's fixed development key,
# published by Microsoft, not a secret. On real Azure: the connection string comes from Key Vault
# (later replaced by Workload Identity), never from this file.
SERVICE_BUS_CONNECTION_STRING=Endpoint=sb://servicebus;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;
SERVICE_BUS_QUEUE_NAME=job-board-status
No quotes, as always since Part 16. The ; and = inside the value are fine: only the first = on the line separates the name from the value.
How I tested it
The pytest suite still covers only the AWS path, and Service Bus tests come in a later step. So these checks ran against the emulator in one-off containers:
docker compose run --rm --no-deps -e CLOUD_PROVIDER=azure api ...
run –rm makes a new container and removes it afterwards. It uses the bind mount, so the current code runs without a rebuild. –no-deps doesn’t start the dependencies, because they’re already running.
Check 1: the switch
- aws: SQSQueue http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/job-board-status, and hasattr(settings, ‘SERVICE_BUS_QUEUE_NAME’) is False.
- azure: ServiceBusQueue sb://servicebus/job-board-status, storage is AzureStorage, and hasattr for both SQS_QUEUE_NAME and AWS_REGION is False.
The class name proves the switch. The URL has no SharedAccessKey, so it’s safe to log. And hasattr(…) is False proves each cloud really runs without the other’s variables. The first run of this check printed True, and that’s how this check paid for itself (problem 1 below).
Check 2: a round trip through my interface
q = get_queue()
sent = q.send({"type": "test", "n": 1})
[m] = q.receive(max_messages=10, wait_seconds=5)
print("same id:", m.id == sent, "body:", m.body)
q.delete(m)
The result: same id: True body: {‘type’: ‘test’, ‘n’: 1}, and a peek afterwards found 0 messages.
- m.id == sent: the ID send returned is the one receive reports, so the publisher’s log line and the worker’s log line can be matched.
- Why peek, not another receive? A message that was received but not completed stays locked for 30 seconds, so a receive in that time would also return nothing. Peek sees locked messages too, so 0 from a peek really means “removed”.
Check 3: not deleted means redelivered, and the old lock is rejected
sent = q.send({"type": "test", "n": 2})
[first] = q.receive(max_messages=10, wait_seconds=5)
time.sleep(32)
[again] = q.receive(max_messages=10, wait_seconds=10)
print("redelivered:", again.id == sent, "new lock token:", again.receipt_handle != first.receipt_handle)
q.delete(again)
try:
q.delete(first)
except Exception as exc:
print("old lock rejected:", type(exc).__name__)
This is the worker’s “handler failed” path. The message isn’t deleted, so it must come back after the 30-second lock, plus a margin. The result: redelivered: True new lock token: True, and old lock rejected: ServiceBusError. Each delivery gets a new lock token, and an old one fails with an error the worker already handles.
Check 4: ping in every broker state
Two pings in one process, timed with time.monotonic(), a clock that never jumps:
- Up: 1004 ms ok, 1003 ms ok. About 1 second is the emulator’s connect, login and attach time.
- Missing queue: 2001 ms ServiceBusError. It does report a failure, but as a timeout, not “not found” (see the limitations below).
- Stopped: 4 ms and 2 ms, ServiceBusConnectionError: … [Errno -3]. Error -3 is a DNS failure: a stopped Compose container’s name stops resolving. Fast.
- Frozen: 2001 ms Ping timed out after 2 s, then 0 ms Previous ping still running…, and the process exited by itself (exit=0). The deadline holds where the SDK would hang forever, and the stuck thread blocks new attempts instead of piling up.
Check 5: the AWS path didn’t change
The full suite: exit code: 0, 203 passed, but coverage dropped to 90.99%, because none of ServiceBusQueue is tested yet. It’s still above the 80% gate. AWS readiness still said queue ok, in 49.1 ms.
Problems I hit
1. The Azure app still loaded the SQS settings
Check 1 printed True for hasattr(settings, ‘SQS_QUEUE_NAME’) in Azure mode. The new settings block I was given had placeholder comments, like # … the rest of your S3 lines, unchanged …. It was pasted above the old block instead of replacing it. So the old queue lines still ran for both clouds, and the old storage block silently filled in what the placeholders left out. Deleting just the old block would have been wrong: the new block was incomplete, so storage would have broken on both clouds. The fix was a Python script that replaced lines 39 to 92 with one complete block, with no placeholders. Three asserts checked the boundary lines first, and it kept a backup. Then py_compile said syntax OK, there was one if, nothing was left outside the branches, and hasattr returned False False. This is the third placeholder problem in Phase 6: <version-from-above> in Part 23, <SB_TAG> in Part 24, and now this. The lesson is now very clear: never use a “fill in the rest” block for a file that gets edited by hand. Use the complete block, or a script that checks before it changes anything.
2. My line-number print hid the indentation
I printed the file with awk ‘{…; print}’ to see line numbers. But awk rebuilds each line from its fields joined by single spaces, so every indent disappeared from the display, and the file looked broken. The file itself was fine. grep -n “” or cat -n keep the whitespace.
3. The Azure SDK flooded the output
The azure.servicebus._pyamqp loggers printed an INFO line for every AMQP state change, and that cut off the results of checks 3 and 4. The fix was the “azure”: {“level”: “WARNING”} line in LOGGING from Part 23. It covers azure.servicebus too, because every Azure SDK logger is a child of azure.
4. A frozen test that wasn’t really frozen
My first “frozen” test passed too easily: ConnectionRefusedError in 2 ms. A frozen broker shouldn’t refuse anything. It should hang. The cause: I waited sleep 15 after docker compose start, but the emulator needs about 28 seconds to be ready (I measured it). So I paused a container that wasn’t listening yet. The fix: wait for Successfully Up in the logs since the restart (–since “$T”), and ping once successfully before pausing. A test that passes for the wrong reason is worse than one that fails.
5. A wrong expectation
I expected the AWS URL to be http://localstack:4566/…, but LocalStack returns http://sqs.us-east-1.localhost.localstack.cloud:4566/…. That’s just LocalStack’s own host format, not a bug.
Known limitations
- A missing queue shows up as a ping timeout, not as “not found”. /readyz still reports fail, but the error name is misleading. I haven’t checked whether real Azure rejects it faster.
- The queue check in /readyz takes about 1 second on Azure, compared with about 50 ms on SQS. When I configure Kubernetes readiness probes, timeoutSeconds must be above that.
- Two /readyz requests at the same moment in one process: the second sees “previous ping still running”, even with a healthy broker. It’s a non-critical check, so the HTTP status doesn’t change, and one prober per pod makes it rare.
- send and receive open connections too, so the same login hang could block them on a frozen broker. The publisher runs inside a web request, so it could hang that request. I marked this to test with the real API and worker, and that’s exactly what Part 26 found.
AWS vs Azure: where the time limits live
The biggest difference this part showed me isn’t in any method name. It’s this:
- botocore has one Config with connect_timeout and read_timeout, and they limit every stage of a call. A frozen LocalStack ends cleanly at the read timeout.
- The Service Bus SDK limits operations and link opens with try_timeout, but not the AMQP login. A frozen broker can hang a fresh connection forever.
So on Azure, the time budget for a dependency (the rule from Part 13) has to be built around the SDK, in my own code, not configured inside it. The second difference is state. An SQS call is complete in itself. A Service Bus client holds a connection and links that can break and must be reset. That’s why ServiceBusQueue has recovery code (_discard) that SQSQueue doesn’t need, and a lock around the sender that SQSQueue doesn’t need either.
What I learned
- One interface, two implementations: get_queue() is the only place that knows the cloud.
- A tuple of base exception classes keeps error handling cloud-neutral.
- Settle on the receiver that holds the lock. A map from lock token to message bridges two separate calls.
- Read the SDK’s thread-safety notes. boto3 is thread-safe; the Service Bus SDK isn’t.
- Reset long-lived connections after errors, or one broken link becomes permanent.
- Measure before tuning. Every ping took about 1 second, so a 1-second limit could never work.
- faulthandler finds where a hang is, in two lines, without a debugger.
- A thread with join(timeout) gives a deadline the library can’t take away.
- acquire(blocking=False) keeps it to one stuck thread at most.
- A test that passes for the wrong reason is a false pass. Wait until the thing you’re testing is really ready.
What comes next
The class works in isolated checks. In Part 26, the real API and worker run on Service Bus, end to end. That run found exactly the problem I listed above: a broker outage made a user’s request wait 12 seconds, and a frozen broker turned one message into 4 copies.