study 01 of 03
Webhook, queue, and worker
Durable bot message ingestion: webhook acknowledges instantly, job enters BullMQ queue, worker pool processes idempotently with exponential-backoff retry.
The problem
Telegram bot webhooks arrive at unpredictable rate. Processing inline within the webhook handler ties response latency to the external API call latency, and a crash during processing discards the message with no retry path.
Constraints
- Webhook endpoint must respond in < 3 seconds or Telegram re-sends.
- Every message must be processed exactly once, even under re-delivery.
- Worker failures must not lose messages. Retries have to be automatic and bounded.
- Observable: every job state (queued, active, failed, completed) must be queryable.
Architecture
Hover, tap, or tab into a box to read what it does.
Trade-offs
BullMQ over in-process queue
instead of Simpler in-memory array
Redis persistence survives a process restart. An in-memory array is faster but loses every job on crash, which is not acceptable for a message bot.
Deduplication by update_id at webhook
instead of At-most-once delivery (discard re-sends)
Telegram re-sends on non-200 response. Checking update_id before enqueueing prevents duplicate jobs without relying on worker-level idempotency alone.
Exponential backoff with jitter
instead of Fixed-interval retry
Fixed retry causes a thundering herd when the API is down. Jitter spreads retries over time, and the Telegram API handles that much better.
What I'd change
- Add a dead-letter queue for jobs that exhaust their retries. Right now they fail silently.
- Separate the 'send reply' call into its own rate-limited queue per chat_id to avoid cross-chat throttling.
- Structured log emission per job state for aggregation (instead of console.log).