Many applications need to know when something has changed.
A client may need to know when an order is completed, a payment is confirmed, a background job finishes, a document is processed, or a long-running operation reaches a new state. A simple solution is often to ask the server repeatedly:
Is it ready?
Is it ready?
Is it ready?
Is it ready?
This is polling.
Polling is easy to understand and easy to implement, but it becomes inefficient when many clients are waiting for changes. The server receives requests even when there is nothing new to report. The client also needs to choose a polling interval, which creates a trade-off between responsiveness and unnecessary traffic.
Event-driven APIs solve this problem differently. Instead of repeatedly asking whether something happened, the application publishes an event when the state changes and interested consumers receive that event.
A simple architecture looks like this:
Traditional Polling
Client
|
| GET /orders/123/status
v
API
|
| "Still processing"
v
Client
|
| GET /orders/123/status
v
API
An event-driven architecture changes the interaction:
Event Driven
Order Service
|
| OrderCompleted
v
Event Broker
|
+------> Notification Service
|
+------> Analytics Service
|
+------> Client-facing Service
The difference is not only about performance. Event-driven design changes how systems communicate, how failures are handled, and how clients receive information.
Why Polling Becomes a Problem
Polling is not always wrong.
For simple applications with a small number of clients, polling may be the easiest and most reliable solution.
The problem appears when polling becomes the default communication mechanism for every state change.
Consider an application with 10,000 active clients. If every client checks an endpoint every five seconds, the system can receive a large number of requests even when only a small percentage of resources actually change.
For example:
10,000 clients
5-second polling interval
10,000 / 5
= 2,000 requests per second
This does not mean every application with 10,000 clients will produce exactly that workload, but it demonstrates the basic problem.
Most of those requests may return:
{
"status": "processing"
}
The server performs work simply to tell the client that nothing has changed.
Event-Driven APIs Change the Communication Model
An event-driven API allows a system to communicate when an event actually occurs.
For example, instead of asking repeatedly whether an order is complete, the order service can publish:
{
"eventType": "OrderCompleted",
"orderId": "ORD-1024",
"completedAt": "2026-11-18T10:30:00Z"
}
The event can then be consumed by another service or translated into a client notification.
This creates a push-oriented flow:
Order Updated
|
v
Event Published
|
v
Consumer Receives Event
|
v
Client Notification
The client no longer needs to continuously ask whether the state has changed.
Separate Commands From Events
A useful event-driven design starts by separating commands from events.
A command represents something a system wants another system to do.
For example:
CreateOrder
CancelOrder
ProcessPayment
GenerateInvoice
An event represents something that already happened.
For example:
OrderCreated
OrderCancelled
PaymentProcessed
InvoiceGenerated
This distinction is important.
A command is generally directed toward a specific handler.
An event describes a fact that other components may be interested in.
For example:
Client
|
| CreateOrder
v
Order API
|
| OrderCreated
v
Event Broker
|
+----> Email Service
|
+----> Inventory Service
|
+----> Analytics Service
The Order API does not need to know exactly which consumers will use the event.
That reduces coupling between services.
Choose the Right Event Transport
There is no single technology that every event-driven API should use.
The transport depends on the communication requirement.
Technology | Best suited for | Typical behavior |
|---|
Webhook | Server-to-server notifications | Receiver gets HTTP request |
Server-Sent Events | Server-to-browser updates | One-way streaming |
WebSocket | Interactive real-time communication | Two-way connection |
Message broker | Service-to-service events | Durable asynchronous processing |
Queue | Background work | Consumer processes messages |
Long polling | Simple compatibility scenarios | HTTP request waits for changes |
The important design question is not:
Which technology is most modern?
Instead ask:
What communication behavior does the application actually need?
Webhooks for Server-to-Server Events
Webhooks are useful when one system needs to notify another system after an event occurs.
For example:
Payment Provider
|
| POST /webhooks/payment
v
Your API
|
v
Process PaymentCompleted
A webhook payload might look like:
{
"eventId": "evt-7821",
"eventType": "PaymentCompleted",
"paymentId": "pay-1001",
"amount": 1499,
"currency": "INR"
}
The receiving API should process the webhook safely because external systems may retry delivery.
This leads to an important requirement: idempotency.
If the same event arrives twice, processing it twice should not create duplicate business effects.
Build Idempotent Event Handlers
An event-driven system should assume that duplicate delivery can happen.
For example, a payment webhook may be delivered twice.
The application can store the event ID:
Event ID: evt-7821
Status: Processed
Before processing another event with the same ID, check whether it has already been handled.
A simplified database table might look like:
ProcessedEvents
event_id processed_at
----------- -------------------
evt-7821 2026-11-18 10:30:00
The application can then use logic similar to:
if (await eventStore.ExistsAsync(eventId))
{
return;
}
await eventStore.MarkAsProcessedAsync(eventId);
await ProcessEventAsync(event);
In production, the check and insert should be designed to be atomic. Otherwise, two concurrent deliveries can both pass the existence check.
A database unique constraint is often useful:
CREATE UNIQUE INDEX ux_processed_events_event_id
ON processed_events(event_id);
Idempotency is one of the most important reliability features in event-driven systems.
Use a Message Broker for Internal Events
For service-to-service communication, a message broker can provide more reliable event delivery.
The architecture can look like this:
Order Service
|
| OrderCreated
v
Message Broker
|
+----> Inventory Service
|
+----> Email Service
|
+----> Analytics Service
The producer does not need to wait for every consumer to finish.
This is especially useful when consumers perform slow operations.
For example, creating an order should not necessarily wait for:
Email generation
Analytics processing
Search indexing
Notification delivery
Those operations can react to the OrderCreated event independently.
Use Outbox Pattern for Reliable Events
One of the most common problems in event-driven applications occurs when a database update succeeds but event publishing fails.
Consider this sequence:
1. Save order to database
2. Publish OrderCreated
If step 1 succeeds and step 2 fails, the database says the order exists but consumers never receive the event.
The transactional outbox pattern addresses this problem.
Instead of writing only the business record:
Orders
the application also writes an event record in the same database transaction:
Orders
OutboxEvents
The flow becomes:
Transaction
|
+----> Save Order
|
+----> Save Outbox Event
|
v
Commit
|
v
Background Publisher
|
v
Message Broker
A simplified table could look like:
CREATE TABLE outbox_events
(
id UUID PRIMARY KEY,
event_type VARCHAR(200) NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMP NOT NULL,
published_at TIMESTAMP NULL
);
A background worker can then publish unpublished events.
This approach prevents the application from relying on two unrelated operations succeeding independently.
Avoid Turning Events Into Another Polling System
An event-driven architecture can still accidentally become a polling architecture.
For example, imagine a background service that repeatedly checks:
SELECT *
FROM outbox_events
WHERE published_at IS NULL;
every second.
This is technically processing events, but the publisher itself is polling the database.
That may be acceptable for some systems, especially when the polling interval is controlled and the workload is small. However, it is important to understand the trade-off.
Better designs can use database notifications, broker-native publishing, change data capture, or other mechanisms where appropriate.
The important point is that removing polling from the client does not automatically eliminate every form of polling from the architecture.
Server-Sent Events for Browser Updates
Server-Sent Events, or SSE, are useful when the browser needs a continuous stream of server-to-client updates.
A browser can establish a connection:
const events = new EventSource('/api/events');
events.onmessage = event => {
const data = JSON.parse(event.data);
console.log(data);
};
The server can then send events as they become available.
For example:
Browser
|
| EventSource connection
|
v
API
|
| OrderCompleted
|
v
Browser
SSE is useful when communication is primarily one-way.
If the application requires frequent two-way communication, WebSockets may be more appropriate.
WebSockets for Two-Way Communication
WebSockets provide a persistent connection between the client and server.
They are useful for applications such as:
Collaborative editing
Live dashboards
Multiplayer applications
Real-time chat
Interactive monitoring
The communication model is:
Client <================> Server
WebSocket
Both sides can send messages over the connection.
However, WebSockets introduce connection lifecycle management, scaling considerations, authentication handling, and reconnect logic.
Do not choose WebSockets simply because the application needs real-time updates. If the client only needs server-to-client notifications, SSE may provide a simpler model.
Handle Event Ordering Carefully
Distributed systems cannot always guarantee that events will arrive in the same order they were generated.
For example:
OrderCreated
OrderPaid
OrderShipped
A consumer might receive:
OrderCreated
OrderShipped
OrderPaid
If the consumer assumes perfect ordering, this can create incorrect application state.
Events should therefore include enough information for consumers to determine their meaning.
A useful event might contain:
{
"eventId": "evt-1002",
"eventType": "OrderShipped",
"aggregateId": "order-1001",
"version": 3,
"occurredAt": "2026-11-18T10:40:00Z"
}
The version can help a consumer determine whether an event is older or newer than the state it already processed.
The exact strategy depends on the broker and business requirements.
Handle Event Failures With Retries
Events can fail for temporary reasons.
For example:
Event
|
v
Consumer
|
X Database temporarily unavailable
The event should not necessarily be discarded immediately.
A retry policy can attempt processing again:
Attempt 1
|
X
|
Attempt 2
|
X
|
Attempt 3
|
v
Success
For persistent failures, use a dead-letter or failure queue where supported.
Avoid infinite retries because a permanently invalid event can consume resources indefinitely.
Secure Event Endpoints
Event-driven APIs still need normal API security controls.
For webhooks, verify the sender.
Common approaches include:
For example, a webhook signature can be calculated using a shared secret:
const crypto = require('node:crypto');
const signature = crypto
.createHmac('sha256', secret)
.update(rawBody)
.digest('hex');
The application should compare the calculated signature with the signature supplied by the sender.
Use constant-time comparison methods for security-sensitive signature checks.
Also validate:
Event type
Event ID
Timestamp
Payload schema
Required fields
Never trust an incoming event simply because it came to a known endpoint.
Version Event Contracts
Event schemas can live longer than the applications that originally created them.
For example:
{
"eventType": "OrderCreated",
"orderId": "ORD-1001",
"customerId": "CUS-5001"
}
A later version might add:
{
"eventType": "OrderCreated",
"orderId": "ORD-1001",
"customerId": "CUS-5001",
"currency": "INR"
}
Adding optional fields is generally easier for consumers than changing or removing existing fields.
Avoid changing event meaning without versioning or coordinating all consumers.
Event contracts should be treated as APIs.
Monitor Event-Driven Systems
Traditional API monitoring focuses heavily on HTTP response time and error rates.
Event-driven systems need additional metrics.
Monitor:
A useful metric is event age.
For example:
Event created: 10:30:00
Event processed: 10:30:03
Event age = 3 seconds
If event age suddenly increases, consumers may be falling behind.
This can be more useful than simply checking whether the API itself is healthy.
Common Mistakes
Replacing Polling With WebSockets Everywhere
WebSockets are not automatically the correct replacement for polling.
Choose the communication model based on the requirement.
Publishing Events Without Idempotency
Duplicate delivery can happen.
Consumers should be designed to safely process repeated events.
Losing Events Between Database and Broker
Updating the database and publishing an event as unrelated operations can create consistency problems.
The outbox pattern can help.
Ignoring Event Ordering
Consumers should not blindly assume that events always arrive in the order they were created.
Retrying Forever
Infinite retries can overload a system.
Use bounded retries and a failure-handling strategy.
Changing Event Contracts Without Planning
Event consumers may be deployed independently.
Treat event schemas as long-lived contracts.
Best Practices
A practical event-driven API design should follow these principles.
Define the business event clearly.
Separate commands from events.
Select the transport based on the communication requirement.
Make event consumers idempotent.
Use an outbox pattern when database and event publishing need reliable coordination.
Design for duplicate delivery.
Handle retries and permanent failures separately.
Define event schemas carefully.
Plan for event versioning.
Monitor event age and consumer lag.
Secure webhook and event endpoints.
Test failure scenarios instead of testing only the successful path.
The most important principle is to design for failure from the beginning. Distributed event processing will eventually encounter retries, duplicate messages, unavailable consumers, delayed events, and partial failures.
Advantages and Disadvantages
Approach | Advantages | Disadvantages |
|---|
Polling | Simple and easy to implement | Unnecessary requests and delayed updates |
Webhook | Simple server-to-server notifications | Requires endpoint availability and security |
SSE | Simple server-to-client streaming | Primarily one-way |
WebSocket | Real-time two-way communication | More connection and scaling complexity |
Message broker | Reliable asynchronous service communication | Additional infrastructure |
Outbox pattern | Stronger database-event consistency | Adds storage and background processing |
The right architecture depends on the application's scale, latency requirements, reliability requirements, and operational maturity.
When Polling Is Still the Right Choice
Event-driven architecture should not become a rule that eliminates polling completely.
Polling can be appropriate when:
The state changes rarely.
There are very few clients.
Real-time updates are unnecessary.
The API is simple.
Infrastructure must remain minimal.
The external system does not support events.
For example, checking a long-running job every few minutes may be perfectly reasonable.
The goal is not to remove polling at any cost.
The goal is to avoid unnecessary polling when the system already has a reliable way to notify consumers about state changes.
Summary
Event-driven APIs provide a better communication model for applications that need to react to changes without repeatedly asking whether something happened.
Polling remains useful for simple scenarios, but it can generate unnecessary traffic and introduce delays when used at scale. Events allow the system to publish information when a meaningful state change occurs.
The implementation can use webhooks, Server-Sent Events, WebSockets, queues, or message brokers depending on the problem being solved.
Reliable event-driven systems also need idempotent consumers, retry handling, event versioning, monitoring, security, and a strategy for coordinating database changes with event publishing.
The most effective design is not the one with the most infrastructure. It is the one that matches the application's communication requirements while keeping delivery reliable, observable, secure, and easy to operate.
Join the conversation! Your thoughts help the community grow.