Sub topic 4
Accepting notification events
This chapter covers the front door of the notification system: the API that producers call to say "something happened, tell the user". It assumes you know HTTP status codes and JSON, understand what a message queue does, and can read short Python snippets. Queues, workers and retries get their own chapters, so here they appear only where the ingestion service touches them.
What the ingestion layer is for
Producers are the order service, the billing service, the social feed and so on. They know what happened. They should not know which channels exist, what the user prefers, or which provider is up today. The ingestion layer takes the producer's description of the event, checks it, stores it durably, and returns quickly.
Keeping this layer thin has three effects:
- Producers stay decoupled from channel details, so adding a channel does not change any producer.
- A slow or failing provider cannot slow down a producer's request, because the API only hands work to a queue.
- One validated, uniform event shape reaches everything downstream.
The event contract
An event is a request to notify, not a rendered message. It carries identifiers and data, and the template and channel decisions happen later.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class NotificationEvent:
event_id: str
user_id: str
type: str
priority: str = "normal"
payload: dict = field(default_factory=dict)
event = NotificationEvent(
event_id="evt-1001",
user_id="user-42",
type="order_shipped",
payload={"order_id": "A-77"},
)| Field | Purpose | Who sets it |
|---|---|---|
| `event_id` | Unique id, used for deduplication and tracing | Producer |
| `user_id` | The recipient whose preferences apply | Producer |
| `type` | Key for preference lookup and template selection | Producer, from a known list |
| `priority` | Decides queue and quiet-hours behavior | Producer, validated by the service |
| `payload` | Data the template needs | Producer |
The producer generates event_id, not the notification service. If the service generated it, a producer that times out and retries would create a second event, and the service could not tell the two apart. When the producer owns the id, a retry carries the same id and can be recognized as a repeat.
Do not put contact details such as phone numbers or email addresses in the event. Resolve them later from the user profile. That way a changed address applies immediately, and events sitting in a queue hold less personal data.
The request path
The response is 202 Accepted, not 200 OK or 201 Created. It tells the producer that the event was taken for processing and that nothing has been sent yet. Returning 200 would suggest the user was notified, and producers would start to rely on that.
A working ingestion handler
The sketch below uses an in-memory set and queue.Queue in place of a shared store and a real broker. It shows the order of the checks and the status codes, and it runs as written.
import queue
from dataclasses import dataclass, field
VALID_PRIORITIES = {"low", "normal", "high", "critical"}
@dataclass(frozen=True)
class NotificationEvent:
event_id: str
user_id: str
type: str
priority: str = "normal"
payload: dict = field(default_factory=dict)
class ValidationError(Exception):
pass
def parse_event(body):
for name in ("event_id", "user_id", "type"):
value = body.get(name)
if not isinstance(value, str) or not value:
raise ValidationError(f"{name} is required")
priority = body.get("priority", "normal")
if priority not in VALID_PRIORITIES:
raise ValidationError(f"unknown priority: {priority}")
payload = body.get("payload", {})
if not isinstance(payload, dict):
raise ValidationError("payload must be an object")
return NotificationEvent(
event_id=body["event_id"],
user_id=body["user_id"],
type=body["type"],
priority=priority,
payload=payload,
)
class IngestionService:
def __init__(self, known_types):
self.known_types = known_types
self.events = queue.Queue()
self._accepted = set()
def handle(self, body):
try:
event = parse_event(body)
except ValidationError as exc:
return 400, {"error": str(exc)}
if event.type not in self.known_types:
return 422, {"error": f"unknown type: {event.type}"}
if event.event_id in self._accepted:
return 202, {"event_id": event.event_id, "status": "duplicate"}
self._accepted.add(event.event_id)
self.events.put(event)
return 202, {"event_id": event.event_id, "status": "accepted"}
service = IngestionService(known_types={"order_shipped", "password_reset"})
body = {"event_id": "evt-1001", "user_id": "user-42", "type": "order_shipped"}
print(service.handle(body))
print(service.handle(body))
print(service.handle({"user_id": "user-42", "type": "order_shipped"}))
print(service.handle({**body, "event_id": "evt-1002", "type": "nope"}))The first call returns accepted, the second returns duplicate with the same 202, and the last two return 400 and 422.
Design decisions and edge cases
Validate the shape, not the user's wishes
Validation here covers structure: required fields, known types, known priorities. It does not decide whether the user wants the notification. Preferences, quiet hours and opt-outs are applied after ingestion, so an opted-out user's event is still accepted. The next chapter covers that stage.
Use 400 for malformed requests and 422 for well-formed requests the service cannot honor, such as an unknown type. Producers can then tell a bug in their payload from a missing registration.
Answer duplicates with the same success
A producer that retries after a network timeout does not know whether the first request arrived. If the second request gets an error, the producer may retry forever or give up. Returning 202 for a repeated event_id makes retries safe. Marking the response duplicate helps debugging without changing the producer's behavior.
Make "seen" and "enqueued" one step
In the sketch, the id is recorded before the event is queued. If the process crashes between the two lines, the id is marked seen but the event was never queued, and every retry is then reported as a duplicate. The notification is lost.
There are two common fixes:
- Write the event and its id to one database transaction, and let a separate relay publish to the queue (the outbox pattern).
- Publish to the queue first and accept an occasional duplicate, which a later idempotency check at the channel worker removes.
Option 2 is simpler. Option 1 avoids the duplicate and suits systems where each stage must be exact.
Protect the front door
- Authenticate each producer, and record which producer sent each event.
- Rate limit per producer, so a runaway job cannot fill the queue and delay everyone else.
- Cap the request body size and the
payloadsize. An unbounded payload becomes an unbounded queue message. - Allow batch submission, such as
POST /v1/events:batch, for producers that emit thousands of events. Report a result per event, because one bad event should not reject the other 999.
Fan-out belongs after ingestion
Some events target many users, such as "new feature released". Accepting one event with a million recipients and expanding it inside the request would block the API. Accept a single campaign event, then let a background step expand it into per-user events.
Common errors
- Generating
event_idon the server. Producer retries then create duplicates. - Returning 200 after enqueue. Producers read it as "delivered" and skip their own error handling.
- Validating
typeagainst a free-form string. A typo such asorder_shipedsilently loses the user's preference lookup and template. Keep a registry of known types. - Putting rendered text in the event. Localization and template changes then require changes in every producer.
- Keeping dedup keys forever. Set an expiry, such as 24 hours, longer than any producer's retry window.
Exercise
A producer sends an event, the request times out, and the producer retries with the same event_id. The first request had in fact succeeded. What should the API return for the retry, and why? Name one failure that can still lose the event even if the API behaves correctly.
Show answer
It should return 202 Accepted, ideally marked as a duplicate, without enqueuing a second copy. A success response lets the producer stop retrying, and the repeated id shows this is the same event. The event can still be lost if the service records the id as seen and then crashes before the event reaches the queue, because later retries are then treated as duplicates. Writing the id and the event in one transaction (an outbox) or enqueuing first avoids this.