Prompt
How do I set up event-driven backend code for HTTP requests and queues?
Latest observation
A good way to build event-driven backend code for both HTTP requests and queues is to separate:
-
transport handling
- HTTP controllers / route handlers
- queue consumers / workers
-
business logic
- services / use-cases
- domain events
-
event dispatching
- emit internal events after work succeeds
- subscribe handlers to those events
That gives you one core flow that can be triggered by either an HTTP request or a queue message.
Recommended architecture
1) Keep HTTP and queue handlers thin
They should only:
- validate input
- convert incoming data into a command/request object
- call the same application service
- return/ack success or failure
2) Put real work in application services
Example responsibilities:
- create user
- charge payment
- send notification
- persist data
3) Publish domain/application events from services
Examples:
UserCreatedOrderPaidEmailRequested
Then attach event listeners:
- send email
- update read model
- publish to another queue
- audit logging
Typical flow
HTTP request flow
- Request hits
POST /orders - Controller validates input
- Controller calls
CreateOrderService - Service saves order
- Service emits
OrderCreated - Event handlers run:
- send confirmation email
- enqueue downstream jobs
- update analytics
Queue flow
- Worker receives message
- Worker validates payload
- Worker calls same service or use-case
- Service processes it
- Service emits events
- Event handlers run
Example structure
src/
http/
controllers/
middleware/
queue/
consumers/
jobs/
application/
services/
commands/
events/
domain/
models/
events/
infrastructure/
db/
message-bus/
queue/
mail/
Simple event-driven pattern
Event emitter
Use an in-process event bus for internal decoupling:
// eventBus.js
import { EventEmitter } from "node:events";
export const eventBus = new EventEmitter();
Service emits event
// orderService.js
import { eventBus } from "./eventBus.js";
export async function createOrder(data) {
const order = await saveOrderToDb(data);
eventBus.emit("order.created", {
orderId: order.id,
userId: order.userId,
});
return order;
}
Event listener handles side effects
// handlers.js
import { eventBus } from "./eventBus.js";
eventBus.on("order.created", async (event) => {
await sendOrderConfirmationEmail(event.userId, event.orderId);
});
HTTP controller
app.post("/orders", async (req, res) => {
const order = await createOrder(req.body);
res.status(201).json(order);
});
Queue consumer
queueConsumer.on("message", async (msg) => {
const payload = JSON.parse(msg.body);
await createOrder(payload);
msg.ack();
});
Important production considerations
1) Use durable queues for reliability
For real queue-based work, use something like:
- RabbitMQ
- SQS
- Kafka
- Redis streams / BullMQ
2) Make handlers idempotent
Queue messages may be delivered more than once.
Make sure processing the same message twice doesn’t break data.
Use:
- unique message IDs
- deduplication tables
- idempotency keys
3) Don’t lose events on DB failure
If you write to the DB and emit an event, consider the outbox pattern:
- save business data + event record in the same DB transaction
- a separate publisher sends the event to the queue/bus
This avoids cases where the DB write succeeds but the event never gets published.
4) Separate sync and async concerns
- HTTP request: usually return quickly
- Queue: do longer tasks asynchronously
- If the user needs immediate result, do it in the request path
- If it can happen later, move it to a queue/event handler
5) Add retries and dead-letter handling
For queue consumers:
- retry transient errors
- send permanently failing messages to a dead-letter queue
- log and alert on repeated failures
6) Use structured logging and tracing
Include:
- request ID
- correlation ID
- message ID
- user ID / order ID
This helps connect HTTP requests to downstream queue processing.
Practical pattern to follow
A very common setup is:
- Controller → calls Use Case
- Queue consumer → calls same Use Case
- Use Case → persists data and emits event
- Event handler → performs side effects
This keeps your system:
- testable
- reusable
- easy to extend
- not tied to one transport
If you want a concrete stack example
I can show this in:
- Node.js/Express + BullMQ
- Node.js/NestJS + RabbitMQ
- Python/FastAPI + Celery
- Go + HTTP + Kafka/SQS
- Java/Spring Boot + Kafka
If you want, I can give you a complete working example in one of those stacks.