
Modern applications often need to process tasks that should not block the main API request. Sending emails, processing payments, generating reports, updating analytics, and handling notifications are common examples.
One approach is to execute everything inside the API request. However, as the application grows, this can increase response times and make services harder to scale independently.
A better approach is to use asynchronous communication between services.
In this guide, we’ll build a small event-driven microservices system using Python, NATS JetStream, and Docker. We’ll create an API service that publishes events and a worker service that consumes them asynchronously.
We’ll also explore how JetStream provides message persistence, acknowledgments, and durable consumers—features that are important when building reliable background-processing systems.
1. What Is Asynchronous Microservice Communication?
In a synchronous architecture, one service calls another service and waits for its response.
For example:
Client → Order API → Email Service → ClientIf the email service is slow, the order API may also become slow.
With asynchronous communication, the API publishes an event and continues without waiting for the worker to finish:
Client → Order API → Message Broker
↓
Email WorkerThe API can return a response while the worker processes the event separately.
This approach helps services:
Operate independently
Scale based on their own workloads
Recover from temporary failures
Reduce direct dependencies between services
Process background work without blocking API requests
However, asynchronous communication introduces its own challenges, including duplicate messages, retries, message ordering, and observability.
That’s where NATS JetStream becomes useful.
2. What Is NATS JetStream?
NATS is a lightweight messaging system designed for communication between distributed services.
NATS Core provides publish-subscribe messaging, while JetStream adds persistence and message-streaming capabilities.
JetStream can store messages and deliver them to consumers later. This is useful when a worker is temporarily unavailable or needs to process messages reliably.
Important JetStream features include:
Streams: Store messages published to configured subjects.
Consumers: Track which messages should be delivered to a service.
Acknowledgments: Allow a consumer to confirm successful processing.
Durable consumers: Preserve consumer state across restarts.
Redelivery: Allow messages to be delivered again if they are not acknowledged.
For this example, we’ll use a stream named ORDERS and a subject named orders.created.
3. Architecture of Our Project
We’ll build a simple order-processing system.
When a client creates an order, the API publishes an order.created event. A background worker receives the event and processes it.
┌─────────────────┐
│ Client / UI │
└────────┬────────┘
│
▼
┌─────────────────┐
│ Order API │
│ FastAPI │
└────────┬────────┘
│ Publish
▼
┌─────────────────┐
│ NATS JetStream │
│ ORDERS Stream │
└────────┬────────┘
│ Deliver
▼
┌─────────────────┐
│ Order Worker │
│ Python │
└─────────────────┘The API and worker are separate processes. They can be deployed and scaled independently.
For example, if order events arrive faster than one worker can process them, we can run more worker instances using a queue-group or shared durable-consumer strategy.
4. Project Structure
Create the following project structure:
async-microservices/
├── app/
│ ├── __init__.py
│ ├── api.py
│ ├── nats_client.py
│ └── worker.py
├── requirements.txt
├── Dockerfile
└── docker-compose.ymlThe API publishes events, the worker consumes them, and nats_client.py contains the shared NATS connection setup.
5. Install the Dependencies
Create requirements.txt:
fastapi
uvicorn[standard]
nats-pyInstall them locally if you want to run the application outside Docker:
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtThe nats-py package provides an asynchronous Python client for NATS.
6. Configure the NATS Connection
Create app/nats_client.py:
import os
import nats
from nats.aio.client import Client as NATS
async def connect_nats() -> NATS:
servers = os.getenv(
"NATS_URL",
"nats://localhost:4222",
)
client = await nats.connect(
servers=servers,
name="order-service",
reconnect_time_wait=2,
max_reconnect_attempts=-1,
)
return clientThe connection uses an environment variable so the same code can run locally or inside Docker.
Inside Docker Compose, the API and worker will connect to the NATS service using its service name:
nats://nats:4222Docker Compose provides internal DNS, so containers can resolve one another by service name.
7. Create the FastAPI Service
The API receives an order request and publishes an event to JetStream.
Create app/api.py:
import json
import os
import uuid
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from app.nats_client import connect_nats
class OrderRequest(BaseModel):
customer_id: str
product_id: str
quantity: int
@asynccontextmanager
async def lifespan(app: FastAPI):
nc = await connect_nats()
js = nc.jetstream()
await js.add_stream(
name="ORDERS",
subjects=["orders.created"],
)
app.state.nats = nc
app.state.jetstream = js
yield
await nc.drain()
app = FastAPI(lifespan=lifespan)
@app.post("/orders")
async def create_order(order: OrderRequest):
order_id = str(uuid.uuid4())
event = {
"event_id": str(uuid.uuid4()),
"event_type": "order.created",
"order_id": order_id,
"customer_id": order.customer_id,
"product_id": order.product_id,
"quantity": order.quantity,
}
try:
await app.state.jetstream.publish(
"orders.created",
json.dumps(event).encode(),
)
except Exception as exc:
raise HTTPException(
status_code=503,
detail="Unable to publish order event",
) from exc
return {
"message": "Order accepted",
"order_id": order_id,
"status": "processing",
}A few important details:
The stream is configured to store messages published to
orders.created.The API publishes a JSON event.
The API returns after JetStream acknowledges the publish.
The worker does not need to be available at the exact moment the API receives the request.
This example treats the event as the order-processing trigger. A production order system should persist the order itself in a database as well.
8. Build the Asynchronous Worker
The worker subscribes to the stream and processes messages.
Create app/worker.py:
import asyncio
import json
from nats.errors import TimeoutError
from nats.js.api import AckPolicy, ConsumerConfig
from app.nats_client import connect_nats
async def process_order(event: dict):
order_id = event["order_id"]
print(f"Processing order: {order_id}")
# Replace this with real business logic:
# - reserve inventory
# - update order status
# - trigger payment workflow
# - publish a follow-up event
await asyncio.sleep(1)
print(f"Order processed: {order_id}")
async def main():
nc = await connect_nats()
js = nc.jetstream()
await js.add_stream(
name="ORDERS",
subjects=["orders.created"],
)
consumer_config = ConsumerConfig(
durable_name="order-worker",
ack_policy=AckPolicy.EXPLICIT,
max_deliver=5,
)
subscription = await js.pull_subscribe(
"orders.created",
durable="order-worker",
config=consumer_config,
)
print("Order worker is running...")
try:
while True:
try:
messages = await subscription.fetch(
batch=10,
timeout=5,
)
except TimeoutError:
continue
for message in messages:
try:
event = json.loads(
message.data.decode()
)
await process_order(event)
# Acknowledge only after successful processing.
await message.ack()
except Exception as exc:
print(f"Message processing failed: {exc}")
# Ask JetStream to redeliver the message.
await message.nak()
finally:
await nc.drain()
if __name__ == "__main__":
asyncio.run(main())Why use explicit acknowledgments?
With explicit acknowledgments, the worker confirms a message only after processing it successfully.
If the worker crashes before acknowledging the message, JetStream can redeliver it.
This helps prevent messages from being silently lost when a consumer fails.
However, redelivery can cause the same event to be processed more than once. That means our worker should be designed to handle duplicate events safely.
9. Add Docker Configuration
Docker makes it easier to run the API, worker, and message broker together.
Create a Dockerfile:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "app.api:app", "--host", "0.0.0.0", "--port", "8000"]Now create docker-compose.yml:
services:
nats:
image: nats:2
command: ["-js"]
ports:
- "4222:4222"
- "8222:8222"
api:
build: .
command: uvicorn app.api:app --host 0.0.0.0 --port 8000
ports:
- "8000:8000"
environment:
NATS_URL: nats://nats:4222
depends_on:
- nats
worker:
build: .
command: python -m app.worker
environment:
NATS_URL: nats://nats:4222
depends_on:
- natsThe -js option enables JetStream.
depends_on controls startup order, but it does not guarantee that NATS is ready to accept connections. The NATS client’s reconnect behavior helps with temporary unavailability. For production, add health checks and readiness handling.
10. Run the Services
Start the complete system:
docker compose up --buildThe services will start:
NATS with JetStream enabled
FastAPI order service
Python order worker
Create an order using curl:
curl -X POST http://localhost:8000/orders \
-H "Content-Type: application/json" \
-d '{
"customer_id": "customer-101",
"product_id": "product-501",
"quantity": 2
}'The API should return a response similar to:
{
"message": "Order accepted",
"order_id": "generated-order-id",
"status": "processing"
}The worker logs should show that it received and processed the event.
To inspect the running containers:
docker compose psTo view worker logs:
docker compose logs -f worker11. Scale the Worker
One benefit of separating the API and worker is that we can scale them independently.
For example:
docker compose up --scale worker=3For a production deployment, configure multiple worker instances to share a durable consumer appropriately. JetStream consumer configuration and delivery behavior should be designed for the intended workload.
Scaling workers does not automatically make every processing operation safe. If multiple workers can process different events that affect the same order or inventory item, use database transactions, locking, or other concurrency controls where needed.
12. Important Production Considerations
A local example is useful for learning, but production systems need more safeguards.
Make event processing idempotent
JetStream can redeliver messages. A worker should be able to process an event more than once without producing duplicate business effects.
One approach is to store each event’s unique event_id in a database with a unique constraint. If the event has already been processed, skip the business operation and acknowledge it.
Configure retries and dead-letter handling
A failed message may be retried several times. Use a retry strategy that distinguishes temporary errors from permanent failures.
For example:
Temporary database issue: retry
Invalid event payload: do not retry indefinitely
Missing required business data: route to a dead-letter or failure stream for investigation
JetStream’s max_deliver limits delivery attempts, but a complete dead-letter workflow requires additional handling and monitoring.
Use the transactional outbox pattern when needed
Suppose the API writes an order to a database and then publishes an event.
If the database write succeeds but publishing fails, the database and message broker can become inconsistent.
The transactional outbox pattern addresses this by storing the order and an outgoing event in the same database transaction. A separate publisher sends pending events to JetStream.
This is especially useful when the event must reliably represent a database change.
Monitor message processing
Track important metrics such as:
Number of messages published
Number of messages processed
Processing latency
Failed processing attempts
Redelivered messages
Consumer pending-message count
These metrics help identify slow workers, failing dependencies, and growing backlogs.
Secure the broker
For production deployments, configure authentication, authorization, TLS, and network access controls. Avoid exposing the NATS client port publicly unless there is a clear requirement.
13. When Should You Use NATS JetStream?
NATS JetStream is useful when your application needs lightweight, persistent asynchronous messaging.
Good use cases include:
Order-processing workflows
Notification services
Background report generation
Event-driven data pipelines
Communication between independently deployed services
Workflows where consumers may temporarily be offline
It may be unnecessary for a small application that only needs a few simple background tasks. In those cases, FastAPI background tasks or a simpler queue may be enough.
Choose the messaging system based on requirements such as persistence, delivery guarantees, operational complexity, throughput, and the need for replay.
Conclusion
Building asynchronous microservices with Python, NATS JetStream, and Docker gives us a practical foundation for event-driven systems.
FastAPI handles incoming requests, JetStream stores and delivers events, and Python workers process them independently. Docker brings the services together in a repeatable local environment.
The most important lesson is that asynchronous messaging is not just about moving work into the background. Reliable systems also need acknowledgments, idempotent processing, retry strategies, observability, and clear ownership of data.
Start with a small event-driven workflow, validate the message lifecycle, and add production safeguards as the system grows.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


