The problem
The app generated an admission PDF report for every applicant and did it inside the same HTTP request: render the document, query the data and email it, all before replying. With ten reports it worked. With hundreds during an academic fair, the server just waited and the interface looked down.
- Long requests hit the proxy timeout and the user saw an error even though the work kept running.
- While a batch was being generated, every API worker was busy and the rest of the app responded slowly.
- If a report failed halfway, there was no way to tell which ones had already been sent: the whole batch had to be redone by hand.
Why a queue
The first idea was to spawn a thread or background task inside the same API. It fixes the timeout, but not the rest: if the process restarts, pending tasks are lost; there are no retries; and the heavy work still competes for the same CPU that serves users.
A queue separates asking for the work from doing it. The endpoint only enqueues one task per report and replies right away; a pool of workers, in separate processes, picks them up and runs them in parallel. Redis stores the pending tasks, so they survive an API restart.
I picked Redis with RQ for a practical reason: Redis was already in the infrastructure, the RQ API fits on one screen and scaling means starting more worker processes. If the system grows, the same design carries over to Celery or another queue without changing the contract with the rest of the app.
Implementation
Enqueue: one task per applicant
The piece that enqueues is small. What matters is what it does before enqueueing: it records every task as pending in the database. That record is what later lets you show a batch's progress and know exactly what is missing.
from redis import Redis
from rq import Queue, Retry
cola = Queue("reportes", connection=Redis.from_url(REDIS_URL))
REINTENTOS = Retry(max=3, interval=[10, 30, 60])
def encolar_reportes(lote_id: str, ids_postulantes: list[int]) -> int:
for id_postulante in ids_postulantes:
registrar_envio(lote_id, id_postulante, estado="pendiente")
cola.enqueue(
generar_y_enviar_reporte,
lote_id,
id_postulante,
retry=REINTENTOS,
failure_ttl=7 * 24 * 3600,
)
return len(ids_postulantes)With that the endpoint is short: it creates a batch identifier, enqueues and returns 202 Accepted with the number of tasks. A second endpoint counts rows by state and the UI polls it every few seconds to draw a real progress bar instead of a spinner.
@router.post("/reportes", status_code=202)
def crear_lote(body: LoteIn):
lote_id = nuevo_lote_id()
encolados = encolar_reportes(lote_id, body.ids_postulantes)
return {"lote": lote_id, "encolados": encolados}
@router.get("/reportes/lotes/{lote_id}")
def estado_lote(lote_id: str):
# {"pendiente": 12, "procesando": 3, "enviado": 180, "fallido": 2}
return {"lote": lote_id, **contar_por_estado(lote_id)}The worker
The function running in the worker does three things in order: generate the PDF, send it and mark the delivery as completed. Each task is independent from the others, so adding capacity means starting another process with the same command.
def generar_y_enviar_reporte(lote_id: str, id_postulante: int) -> None:
# la cola entrega "al menos una vez": si el worker cae a mitad de camino,
# la tarea vuelve a correr, así que lo primero es mirar si ya se hizo
if envio_completado(lote_id, id_postulante):
return
marcar(lote_id, id_postulante, estado="procesando")
pdf = generar_pdf(id_postulante)
enviar_correo(id_postulante, adjunto=pdf)
marcar(lote_id, id_postulante, estado="enviado")Retries and errors
Almost everything that fails in this flow is transient: the email service returns a passing error or a rate limit, or the database takes a while to free a connection. Retrying with growing delays fixes most of them without human intervention.
- Every task is idempotent: generating the same report twice does not duplicate emails.
- Retries wait longer each time (10 s, 30 s, 60 s) so external services are not overwhelmed.
- Whatever fails three times lands in a failed queue with the reason stored, to be reviewed without blocking the rest of the batch.
- A failure alerts the team with the applicant identifier, not a generic message.
def al_fallar(job, connection, tipo, valor, traceback):
lote_id, id_postulante = job.args
marcar(lote_id, id_postulante, estado="fallido", motivo=str(valor))
avisar_equipo(f"Reporte {id_postulante} falló tras {job.retries_left + 1} intentos")
cola.enqueue(
generar_y_enviar_reporte,
lote_id,
id_postulante,
retry=REINTENTOS,
on_failure=al_fallar,
)Enqueueing is easy; the hard part is deciding what happens when something fails.
Knowing what is going on
Moving the work out of the request has a cost: you no longer see the error on the user's screen. Three things made up for it. First, the per-task state in the database, which feeds the progress bar. Second, the failure reason stored next to each failed report. Third, a simple queue dashboard to see how many tasks are waiting and how many workers are active.
What I would do differently
- Define the state of every task in the database from day one, rather than adding it after seeing a half-finished batch.
- Put a concurrency limit per kind of job, so reports do not displace other tasks in the same queue.
- Measure time per task from the start: those numbers tell you how many workers you need without guessing.
- Test the failure path with a test that kills the worker mid-task, not just with simulated exceptions.
Result
The interface stopped freezing, large batches run in parallel and isolated errors no longer force a full redo: every pending, sent or failed report is visible and can be retried individually. Best of all: adding capacity means starting one more worker, not touching the code.