NATS is a lightweight message queue for asynchronous communication between application components. Instead of connecting directly, a web application publishes messages and separate subscribers or handlers process them. section 21.0 section 21.2
A NATS workflow uses three practical ideas:
- Publish an event to a subject, such as events.todo.newitem, rather than writing directly to the database. section 21.2
- Subscribe with a message handler that receives matching events and performs the database operation. section 21.3
- Scale handlers independently; grouped handlers share messages, limiting database connections while queued messages absorb demand peaks. section 21.3
Asynchronous to-do saving
When a user adds a to-do item, the web application publishes a NewItemEvent to events.todo.newitem. A subscriber or save handler consumes it and inserts the item into the database. The application remains responsive under load, but the item may not appear immediately because asynchronous processing creates eventual consistency. section 21.2 section 21.3
# switch to the exercise folder: cd ch21/exercises/todo-list # start the message queue: docker compose up -d message-queue # check the logs: docker container logs todo-list-message-queue-1 # and check active connections: curl http:/./localhost:8222/connz
Run NATS with Docker Compose, inspect its logs, and query the admin API for active connections. section 21.2
# scale up the handlers: docker compose up -d --scale save-handler=3 # check that one of the new handlers has connected: docker logs todo-list-save-handler-2 # browse to http:/./localhost:8080 and add some new items # see which handlers have processed the messages: docker compose logs --tail=1 save-handler
Scale the save handler to three containers and inspect logs to see messages distributed across handlers. section 21.3

