knaxuslearn · build · ship

Projects / Task queue / Wrap up

Wrap up

Keep going

  • Heartbeats. Let a long job renew its lease every few seconds so the lease can stay short.
  • Priorities and named queues. Add a queue and priority column and filter in claim.
  • Jitter. Add a random amount to each backoff so a thousand failed jobs do not all retry at the same second.
  • Dedupe. A unique key so "send the invoice for order 17" can only be queued once.
  • Results. Store the return value of a handler so callers can read it.
  • A different store. Swap SQLite for PostgreSQL and use FOR UPDATE SKIP LOCKED for claiming.

What this version leaves out, and what a real queue does

  • It usually keeps jobs in a server such as Redis, RabbitMQ or PostgreSQL, so workers on many machines can share it. Our file works on one machine.
  • Real workers run jobs with timeouts, in separate processes or threads, so one stuck handler does not freeze the loop.
  • They have heartbeats, priorities, rate limits, schedules and a web dashboard.
  • The "at least once" promise is the same everywhere. Truly "exactly once" delivery needs the handler's cooperation.

Check yourself

Answer each question in your head first, then open it to check.

  1. Why does one UPDATE ... RETURNING stop two workers from taking the same job, when "select, then update" does not?
    The find and the mark happen in a single statement, and SQLite lets one writer run at a time, so a second worker can only start after the first job is already marked running. With two statements, another worker can run in the gap between them.
  2. What does exponential backoff protect, and what would you add so many jobs do not retry in the same instant?
    It protects the service your handler calls (and your own database) from being hammered while it is struggling. Adding a small random amount (jitter) spreads the retries out.
  3. Why can a queue never tell a slow worker from a dead one, and what does a lease do about it?
    From outside, both look the same: no news. A lease turns the question into a time limit. If the worker does not finish before the lease ends, we treat it as gone and let another worker claim the job.
  4. What does the attempt number check in finish prevent?
    A slow worker whose lease expired could come back and mark a job done or failed that another worker now holds. The attempt number no longer matches, so the stale answer is ignored.
  5. Teach it back: a teammate says "just make sure handlers never fail, then we don't need retries or leases". What do you answer?
    Handlers fail for reasons nobody controls: a network call times out, a server is full, a process is killed. Retries handle errors the code raises, and leases handle workers that disappear without raising anything. Both are needed for a job never to be lost.

Sources