Projects / Task queue
Python · about 10 hours · 4 phases
Build a task queue in Python
Your web app has to send a welcome email, resize a photo and charge a card. Doing all that while the visitor waits is slow, and if the process dies halfway, the work is simply lost. A task queue fixes both: the app writes a small note ("send this email") and returns at once, and separate workers pick up the notes and do the work in the background. In about 10 hours you will build a small task queue using only Python's standard library, and then try your best to break it.
You work in four phases of about 2.5 hours each, and every phase ends with something you can run. By the end you will have:
- a queue stored in one SQLite file, with workers that never run the same job twice at the same moment,
- retries with growing waits, delayed jobs and a "dead" state for jobs that can never work,
- a worker that survives
kill -9without losing a job, - a chaos test that kills workers at random while 200 jobs run, and a number for how fast it goes.
You need basic Python (functions, modules, try and except) and a little SQL. Everything else is explained when it first appears.
The four phases
Jobs in a table
You end with a queue file, a worker that drains it, and proof that two workers can share it without running a job twice.
- 1.1 The jobs table30 min
- 1.2 A worker40 min
- 1.3 The obvious way breaks40 min
- 1.4 Why one statement is safe40 min
When jobs fail
You end with retries with growing waits, delayed jobs, and a dead state, so one broken job cannot block or loop forever.
- 2.1 Remember attempts, retry later50 min
- 2.2 Give up on poison jobs40 min
- 2.3 Delayed jobs30 min
- 2.4 Look at the dead30 min
Workers that die
You end with a worker you can kill -9 mid-job, with the job picked up by someone else.
- 3.1 Break it first35 min
- 3.2 Leases55 min
- 3.3 Kill it30 min
- 3.4 When the lease is too short30 min
Stop, watch, and test it hard
You end with a worker that shuts down cleanly, a stats command, a chaos test, and a throughput number.
- 4.1 Stop politely30 min
- 4.2 A stats command40 min
- 4.3 The chaos test40 min
- 4.4 How fast, and where it stops40 min