Every Python team eventually hits the same wall: a background job that outgrows a thread. A webhook needs a retry, a nightly report needs cron semantics, a bulk import needs to run “later” without blocking a request — and suddenly someone proposes a broker, a results database, and a weekend of configuration. For a large slice of projects, that is heavy machinery bolted onto a problem that actually needed one decorator and one worker process.
huey — whose own pyproject.toml describes it as “a little task queue” — takes the opposite trade-off. It is an MIT-licensed task queue by Charles Leifer, at version 3.5.4 in the checkout we examined, and its core package ships with zero required dependencies: you only install redis-py if you point it at a Redis-like broker, or psycopg for Postgres. Despite that, it offers retries with exponential backoff, task priorities, expiration, rate limits, locks, timeouts, crontab-style periodic tasks, groups and chords, result storage, and a consumer that runs workers as threads, greenlets, or processes.
The interesting part for source divers is how little code carries all of that. The public surface lives in one flat module, huey/api.py, at 1,486 lines on the default branch; every storage backend from Redis to SQLite to Postgres sits in a single 1,653-line huey/storage.py; and the consumer is a 698-line huey/consumer.py. No framework, no plugin registry, no indirection between you and the queue. This tour walks through that code with line references, then examines what the flat design buys and what it costs.
Overview of huey's architecture: the public API funnels every call through enqueue, one flat storage module backs the queue, and a small consumer runtime polls it with backoff.
Reading the overview from left to right, the whole system falls out of nine entry points:
- Huey, L53 — the base class that wires one storage backend, one Registry, one Signal hub, and hook dictionaries (
pre_execute,post_execute,on_startup,on_shutdown) into every instance. - task(), L171 — the decorator factory whose single signature carries
retries,retry_delay,retry_backoff,priority,expires, andtimeout; it returns a TaskWrapper, not a function. - enqueue(), L304 — resolves the expiration time, emits the
enqueuedsignal, then callsstorage.enqueue(self.serialize_task(task), task.priority). That one line is the entire “publish” step. - _execute(), L432 — the execution heart: it times the task with
time.monotonic()and routes failures through a typed ladder of exceptions rather than string matching. - Worker.loop(), L120 — the worker’s poll loop: dequeue, execute, and raise
WorkerRecycleoncemax_tasksis hit so long-lived workers restart cleanly. - Worker.sleep(), L143 — empty-queue backoff in two lines: wait for
delay, thenself.delay *= self.backoff, capped atmax_delay. - Scheduler, L151 — the second process: it moves due tasks from the schedule into the queue and, with
periodic_task_seconds = 60, wakes each minute for periodic work. - Message, L7 — the wire format: a 15-field namedtuple holding id, name, eta, retries, retry_delay, priority, args, kwargs, the on-complete and on-error chains, expiry fields, timeout, chord config, and retry_backoff.
- BlackHoleStorage, L311 — the most instructive backend: every interface method is a one-line no-op, which shows exactly how thin the storage contract is.
The detail view: the execution core and its typed exception handling, the seven real storage backends, and the three worker environments that the consumer can spawn.
One flat file: api.py in 1,486 lines
Everything a user imports lives in huey/api.py. The Huey.__init__ defaults at L95 tell you the product philosophy: results=True (store every return value), utc=True (normalize all internal timestamps), immediate=False (debug mode that executes tasks synchronously, optionally swapping in an in-memory broker per create_storage at L133). A subclass only has to set one class attribute — storage_class — to become a new queue flavor; the nine convenience wrappers at the bottom of the file, from RedisHuey at L1473 to FileHuey at L1485, do exactly that and nothing else.
The decorator deserves a second look — it is the whole user-facing contract. @huey.task() produces a TaskWrapper (defined at L936) whose __call__ at L1038 is one line: return self.huey.enqueue(self.s(*args, **kwargs)). The s() helper at L1044 pops per-call overrides like eta, delay, and priority out of the kwargs, normalizes the eta through normalize_time in huey/utils.py, and builds the Task instance. Calling the decorated function never runs your code — it serializes an intent. If you want the local behavior you call .call_local().
Execution is equally explicit. execute() at L413 is a four-way gate: not yet due goes to the schedule, revoked or expired tasks are dropped with a signal, and only survivors reach _execute(). There the timeout machinery wraps the call in the consumer-provided context, and the exception ladder handles TaskTimeout, RateLimitExceeded, TaskLockedException, RetryTask, and CancelExecution as distinct cases, each with its own signal and retry semantics. Failures land in _requeue_task at L572, and huey/exceptions.py closes the loop by defining RETRYING_EXCEPTIONS at L37 — exceptions that should not surface to the result store while a retry is pending.
Eight storage backends in a single file
huey/storage.py is the largest module at 1,653 lines, and it contains the entire persistence layer. BaseStorage at L40 declares the contract in two class attributes: blocking = False (does dequeue() block, or should the worker poll?) and priority = True. Everything else is methods: enqueue/dequeue, add_to_schedule/read_schedule, and a small key-value store for results plus counters for chords.
The backends show how much behavior fits under that contract. MemoryStorage at L335 implements priority with Python’s heapq: enqueue pushes a (-priority, counter, data) tuple, where a monotonically increasing counter preserves FIFO order among equal priorities — a textbook stable-priority-queue trick in four lines. RedisStorage at L453 namespaces four keys per queue (huey.redis.*, huey.schedule.*, huey.results.*, huey.counters.*), uses lpush for the queue, a zadd-scored sorted set for the schedule, and a small Lua script (SCHEDULE_POP_LUA, L445) that pops due schedule entries atomically with zrangebyscore. The SQLite backend at L851 defaults to WAL journaling, an 8 MB page cache, autocommit mode, and a composite index on (queue, priority desc, id) so that dequeuing is an indexed scan; a strict_fifo flag rebuilds the task table with AUTOINCREMENT so recycled rowids cannot reorder tasks. Postgres and a Cython-accelerated SQLite (CySqliteStorage, L1080) round out the set. If you have ever wondered how the embedded database underneath the SQLite source tour behaves as a job store, this file is a compact case study: per-consumer connections, busy timeouts, and explicit index design instead of an ORM.
Serialization is deliberately boring, which is a feature. huey/serializer.py is 91 lines: pickle.dumps at L28, optional gzip or zlib compression at level 6, and a SignedSerializer at L58 that appends an HMAC-SHA1 signature and verifies it with hmac.compare_digest. huey/signals.py adds the observability layer — thirteen constants from SIGNAL_ENQUEUED to SIGNAL_RATE_LIMITED listed at L7-L19, delivered through a Signal class whose receivers dict maps each signal name plus an 'any' catch-all.
The consumer: threads, greenlets, or processes
The consumer is where huey differs most from “just use a loop.” Consumer.__init__ at L392 fixes the tuning knobs: workers=1, initial_delay=0.1, backoff=1.15, max_delay=10.0, scheduler_interval=1 — and one unusual validation: the scheduler interval must divide 60 evenly (L421), because periodic tasks are checked on minute boundaries and a non-divisor interval would drift.
Execution models are abstracted behind an Environment at L230 with three concrete implementations — threads, greenlets, and processes — selected through the WORKER_TO_ENVIRONMENT mapping at L374. The greenlet environment warns loudly if you forgot to apply gevent’s monkey-patching, and the process environment gets a ForkSafeFlag at L210: a stop flag built on a raw os.pipe() because a killed process holding a standard event would hang shutdown. Health checks run by default every 10 seconds, and max_tasks recycles workers after N jobs.
From lpush to bzpopmin: how priorities entered the code
The most interesting engineering story in the tree is how priority support was layered on without breaking the base backend. Plain RedisStorage declares priority = False at L454 — its enqueue at L525 raises NotImplementedError for priorities, because a plain list cannot dequeue by weight.
The fix is a mixin, not a rewrite. RedisPriorityQueue at L746 swaps the list for a sorted set: enqueue becomes zadd with the priority as score (L757), and dequeue becomes bzpopmin when blocking or zpopmin otherwise (L763, L773). PriorityRedisStorage at L785 is then just class PriorityRedisStorage(RedisPriorityQueue, RedisStorage) — composition in one line, gated on Redis 5.0+ where the blocking pop commands exist. The same discipline appears in huey/contrib/sql_huey.py, a peewee-backed storage for any SQL database: its dequeue orders by priority desc, id under FOR UPDATE SKIP LOCKED (L46), and the code probes the server version at startup — MariaDB only gained the clause in 10.6 and MySQL in 8.0.1, and older versions silently fall back to plain FOR UPDATE (L50-L57). Real database-engineering hygiene: feature detection with graceful degradation, not optimistic SQL.
The same minimalism extends outward. huey/contrib/mini.py is a 136-line standalone reimplementation of the queue API for gevent, spawning tasks onto a greenlet pool — evidence of how small the essential core really is. huey/contrib/valkey_glide.py adapts the Redis storage to the Valkey GLIDE client; because that client cannot block, the code comments “Glide can’t block, so results are polled” and disables blocking dequeue (L44). Even the CLI is tiny: huey/bin/huey_consumer.py resolves your Huey instance from an import path and calls consumer.run().
If you run Redis in production for anything — caching, sessions, or this queue — it is worth understanding the server’s own design; our Redis source tour covers that side of the wire protocol huey speaks.
Honest Limits
The flat design has real trade-offs, and the code is candid about them:
- pickle by default. Task payloads are pickled (serializer.py, L28), so a compromised broker can execute arbitrary code in your workers. The
SignedSerializermitigates tampering, but this is a genuine threat model to weigh. - Priorities are opt-in per backend. The default Redis backend rejects them, as does the Valkey GLIDE adapter; you must choose
PriorityRedisHueyor the SQLite/Postgres routes. - No process workers on Windows. The consumer CLI exits with an error if
worker_type=processis requested there (bin/huey_consumer.py, L44); threads are the default. Noneresults are dropped unlessstore_none=True, becauseput_resultis gated on the value not beingNone(api.py, L513). It is widely recognized that this surprises newcomers who enqueue functions returningNoneand then block forever on the result.- Observability is add-on territory. Signals cover the lifecycle, but dashboards live in contrib modules with their own dependencies, and there is no built-in metrics export. When a worker wedges in production, the practical toolkit is external: logs first, then a sampling profiler such as py-spy attached to the consumer to see which task is stuck.
None of these are hidden — each is visible in a few lines of code. When the whole system is a handful of files, you can verify what the queue does with your task between calling the decorator and the worker picking it up. Enjoyed this post? Never miss out on future posts by following us