My API never sends emails (and yours shouldn’t either)
What I learned building TaskForge: move slow work out of the request path with Postgres, Redis and a pool of workers.
Some endpoints do a lot of work: send an email, build a PDF, resize an image, call a slow third-party API. If you do that work inside the request, the client waits for all of it, and your server holds a connection open the whole time. Ten slow requests at once and everything else queues up behind them.
TaskForge is my small demo of the fix: accept the job, store it, return straight away, and let workers do the work.
The shape of it
client --POST /jobs--> api --INSERT--------> postgres (source of truth)
|
+--LPUSH id--> redis (just the queue)
|
| BRPOP
v
workers --UPDATE status--> postgres
The API does two cheap things and replies 202 Accepted:
- Writes the job (type, payload,
status = 'queued') to PostgreSQL. - Pushes the job’s ID, not its payload, onto a Redis list.
The API side
app.post('/jobs', async (req, res) => {
const { type, payload } = req.body;
const { rows } = await db.query(
`INSERT INTO jobs (type, payload, status) VALUES ($1, $2, 'queued') RETURNING id`,
[type, payload],
);
await redis.lPush('jobs', rows[0].id);
res.status(202).json({ id: rows[0].id, status: 'queued' });
});
The handler finishes in a few milliseconds however slow the job is.
The worker side
while (true) {
const item = await redis.brPop('jobs', 0); // blocks until something arrives
const job = await getJob(item.element);
await setStatus(job.id, 'running');
try {
await handlers[job.type](job.payload);
await setStatus(job.id, 'done');
} catch (err) {
await setStatus(job.id, 'failed', String(err));
}
}
BRPOP blocks, so idle workers cost almost nothing. Need more throughput? Start more worker processes. They all pull
from the same list and Redis gives each job to exactly one of them.
Why Postgres and Redis?
Redis is a great queue, but I don’t want it to be the only record that a job exists. Postgres holds the durable state
(what was asked for, when, and what happened), so a GET /jobs/:id endpoint can report status even after Redis has
forgotten the ID.
What I’d add next
- Retries with backoff, using an
attemptscolumn and a delayed re-queue. - A reaper for jobs stuck in
runningafter a worker crash. - Idempotency keys, so a client retrying
POST /jobsdoesn’t enqueue the same email twice.
The general rule: if the user doesn’t need the result to read the response, it doesn’t belong in the request.
The hero animation on my homepage is this exact flow. Click POST /jobs a few times and watch the queue fill up.