Skip to content
Back to skills

Fastapi Async Workers

ASecurity

Background work for FastAPI - choosing between a job queue (commands that must run) and an event stream (facts others react to), Redis Streams with consumer groups, at-least-once delivery with idempotent handlers, XAUTOCLAIM recovery, dedup keys, dead-letter streams, derived counters by recount, separate worker containers and entrypoints, shutdown contract, Redis pub/sub + SSE and LLM token streaming. Use whenever the user mentions workers, queues, background jobs, Celery alternatives, Redis ...

  • 2 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added November 27, 2026
developmentpythongoreactfastapiapidatabase

Works with

  • terminal
  • cli
  • api

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned November 27, 2026

npx -y skills add amralhorimy/fastapi-pro-skills --skill fastapi-async-workers --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Fastapi Async Workers?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Fastapi Async Workers
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/amralhorimy-fastapi-async-workers/badge)](https://www.skillsdirectory.com/skills/amralhorimy-fastapi-async-workers)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: fastapi-async-workers
description: Background work for FastAPI - choosing between a job queue (commands that must run) and an event stream (facts others react to), Redis Streams with consumer groups, at-least-once delivery with idempotent handlers, XAUTOCLAIM recovery, dedup keys, dead-letter streams, derived counters by recount, separate worker containers and entrypoints, shutdown contract, Redis pub/sub + SSE and LLM token streaming. Use whenever the user mentions workers, queues, background jobs, Celery alternatives, Redis streams or pub/sub, SSE, streaming responses, long-running tasks, polling, "wait for the result", notifications pipeline, counters, or splitting a worker into its own container.
---

# Async Workers, Streams, Live Updates

Two different mechanisms - choose deliberately (`references/worker-patterns.md` has code):

| | **Job queue** (`platform/jobs`, stream `jobs:stream`) | **Event stream** (`shared/events.py`, stream `events:interactions`) |
|---|---|---|
| Meaning | a **command** that must be executed once-ish | a **fact** that happened; many parties may care |
| Consumers | one handler per job type | several **independent consumer groups** read the same entry (`counters`, `archive`, `notifications`, `feed-seen`) |
| Delivery | at-least-once; persist terminal outcome before ACK; `XDEL` only for a dedicated job stream after ACK and only when no other group needs it | at-least-once per group; **never XDEL per-consumer**; trimming still risks unread entries in slow groups |
| Producer failure | enqueue errors surface to the caller; a hard capacity contract needs an atomic capacity check + append | Best effort is valid only when event loss is acceptable and observable; otherwise use a transactional outbox |
| Dedup | handlers must be idempotent; atomic `SET NX` + capacity + `XADD` is an implementation requirement, not guaranteed by the illustrative code | archive can use event id as `_id` (duplicate = ignored); this protects that sink only |
| Dead letters | append durable DLQ record before ACK after bounded attempts / explicit permanent error / invalid message | each group records poison events before ACK; never ACK an unrecorded failure |

ADRs behind this: Redis Streams over Celery/ARQ/RabbitMQ/Lists (consumer groups + orphan recovery without a framework; ports
`JobEnqueuer`/`JobRegistry` keep the broker replaceable) and events + derived counters (decoupled modules, no double counting).

## Rules
1. **Idempotent handlers, always.** Duplicates and redeliveries are normal. Use natural keys, conditional updates, `_id = event id`.
2. **Derived data is recomputed, not incremented.** Counters are rebuilt from the source (`$set` of a recount) when an event says "post X
   changed"; bursts for one hot post are coalesced into one recount. A `recount` CLI repairs everything after an outage.
3. **The database is the truth; events/jobs announce.** A dropped event costs freshness only if the domain can tolerate loss and has a repair path.
   If loss is unacceptable (billing, reputation, audit, required cross-service effects), write the state change and an **outbox** record in one
   database transaction; relay/retry idempotently. Publishing after a DB write alone is not atomic.
4. **Publish only after the write succeeded and only on real change** (a second "like" of the same post emits nothing).
5. **Orphans**: periodically `XAUTOCLAIM` entries idle longer than the maximum bounded handler timeout + retry delay + scheduling/network
   margin, or renew the lease while work runs. Bound reclaim count/cadence and task count; size visibility so healthy work is not concurrently
   reclaimed. Poison messages stop after `JOB_MAX_DELIVERIES` and are written to the DLQ before ACK.
6. **Retry only transient errors** with exponential backoff + jitter and a cap; permanent errors fail at once to the dead stream.
7. **Bounded everything**: configure stream retention and an honest capacity policy, bound the number of active tasks, handler timeout,
   Redis/store command timeouts, retry delay/attempts, payload/frame sizes, SSE cleanup, and shutdown drain. A `MAXLEN` approximate trim is not
   a hard saturation guarantee and can remove unread events; a strict capacity promise requires an atomic tested enqueue contract.
8. **Shutdown contract** (document and test it): stop fetching; give in-flight work `drain_timeout`; then cancel remaining tasks without ACK
   so they remain recoverable from the PEL. Persist terminal state/DLQ before any ACK. Log/report drained and abandoned counts and ensure
   cancellation is cooperative; a lost lease/job needs bounded sweeper recovery and alerting.
9. **In-process first, distributed second.** Learn locks/semaphores/queues/backpressure in one process (labs: lock, deadlock, queue,
   semaphore, process lock) before splitting. Then: API only **produces**; consumers run as `python -m <pkg>.entrypoints.worker`
   (same image, own container, `stop_grace_period`), heavy models in their own worker/image (`llm_worker`, `embedding_worker`).
10. **Correlation id travels in the payload** and is re-bound in the worker; job failures log with the id of the request that created them.
11. **Each worker type is its own entrypoint** (composition root) and shares the same module code; test the wiring helper the entrypoint uses.
12. **Message boundary and ACK discipline.** Parse and schema-validate inside the per-message failure boundary. Invalid/permanent messages go to
    a durable DLQ (or durable terminal job state) before ACK. Unknown or infrastructure failures remain pending; never ACK an error merely to
    stop retries. Re-enqueue-then-ACK retries can duplicate after a crash, so handlers remain idempotent.
13. **Be explicit about guarantees.** A reference sketch that omits atomic dedup, hard saturation, lease renewal, or whole-operation deadlines
    does not provide them. Label missing behavior as planned/not implemented and add tests before claiming it.

## Live updates (pub/sub + SSE) and token streaming
- Pub/sub is ephemeral: announce state, never be the only record. Persist the final result once; stream chunks over a per-job channel.
- SSE endpoint order is fixed: **subscribe -> read current state -> send it -> relay -> terminal event ends the stream** (otherwise events
  between read and subscribe are lost). Heartbeat comment ~15 s, detect disconnect, unsubscribe in `finally`, authenticate and check
  ownership. Nginx `proxy_buffering off` on stream routes. Replaces Mongo polling.
- Token streaming: worker (blocking inference in an executor, pushing chunks through an `asyncio.Queue`) publishes `token` events with a
  sequence number; accumulates; persists once; publishes `done`. Single-question route (wait) and chat route (stream) share the same job.
- Chat/WebSocket fan-out: one channel per chat/user with explicit routing and acks rather than one global channel filtered locally
  (known limit of the simple version).

## Splitting a worker out - checklist
- [ ] Handler code importable and unit-tested with fakes; entrypoint only composes
- [ ] Compose service: own command, grace period, resource limits, restart policy; `--scale` works (consumer groups)
- [ ] Kill the worker mid-job -> reclaimed after idle time, final state correct, no duplicate visible effect
- [ ] Redis down -> apply the documented policy for that queue/event: commands fail visibly (for example 503 with `Retry-After`),
      explicitly lossy events may be dropped and counted, or outbox-backed events remain durable; verify recovery rather than assuming it
- [ ] Queue length/pending/lag/dead exported and alerted (`fastapi-observability`)

Files in this skill

  • SKILL.md7.5 KB
  • references/worker-patterns.md13.3 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.