A Lightweight Real-Time Notification System with FastAPI, Redis Pub/Sub, SSE, and React Query
A useful notification feature needs to do two things well:
- Keep a durable history users can return to.
- Show new activity quickly without asking users to refresh the page.
Those are related problems, but they are not the same problem. A database is a good source of truth for notification history. A live connection is useful for timely updates. For a small application, PostgreSQL, Redis Pub/Sub, Server-Sent Events (SSE), and TanStack Query can cover both without introducing a separate broker and worker fleet.
This post walks through that design using a FastAPI backend and a React/Next.js frontend.
Scope: this is a lightweight, best-effort real-time design. It does not promise exactly-once delivery or replay of every event. The database is durable; Redis Pub/Sub is not.
Architecture
Business operation
│
▼
Notification service
├── Insert notification into PostgreSQL
└── Publish a live event to Redis Pub/Sub
│
▼
FastAPI SSE endpoint
│
▼
Browser EventSource
│
▼
TanStack Query cache / UI
Notification history and unread count ──► PostgreSQL
The distinction is important:
- PostgreSQL stores notification history and read/archive state.
- Redis Pub/Sub broadcasts updates to clients listening right now.
- SSE keeps a server-to-browser connection open over HTTP.
- TanStack Query handles history, unread counts, and cache updates in the UI.
If a browser is offline or disconnects, it can fetch the durable notification list when it reconnects. It cannot replay missed Redis Pub/Sub messages.
Backend: persist notifications as domain data
1. Model and schema
Each notification belongs to a user and an organization. That scope should be applied consistently to reads, updates, deletes, and live channels.
from uuid import UUID
from sqlalchemy import (
Boolean,
ForeignKey,
Index,
String,
Text,
text,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
# Change these project imports to match your package and module paths.
from src.app.shared.enums import NotificationCategory
from src.app.shared.mixins import Base, TenantMixin, TimestampMixin, UUIDPrimaryKeyMixin
from src.app.auth.models import AuthUser as User
class Notification(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
__tablename__ = "notifications"
user_id: Mapped[UUID] = mapped_column(
ForeignKey("auth_user.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
title: Mapped[str] = mapped_column(String(255), nullable=False)
body: Mapped[str | None] = mapped_column(Text)
category: Mapped[str] = mapped_column(String(30), nullable=False)
action_url: Mapped[str | None] = mapped_column(String(500))
meta: Mapped[dict | None] = mapped_column(JSONB)
is_read: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
is_archived: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
meta is for optional, structured context such as a trip_id or expense_id. Keep it as JSON data; do not treat it as trusted HTML.
The Pydantic response schema should expose the same identifier and fields in both ordinary API responses and live events:
class NotificationResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: UUID
organization_id: UUID
user_id: UUID
title: str
body: str | None
category: str
action_url: str | None
meta: dict[str, Any] | None
is_read: bool
is_archived: bool
created_at: datetime
In the deployed model, the primary key is a UUID named id. The frontend must use that identifier; it should not assume a numeric pkid.
An Alembic migration creates the table, foreign keys, and indexes. Indexes on (user_id, is_read) and (user_id, is_archived) help the common unread and archive filters.
2. Keep database access in the repository
The repository owns SQLAlchemy queries. Every user-facing query includes both user_id and organization_id; this prevents an ID from another tenant from being used to read or mutate a notification.
def list_query(
self,
user_id: UUID,
organization_id: UUID,
tab: str,
category: str | None,
):
stmt = select(Notification).where(
Notification.user_id == user_id,
Notification.organization_id == organization_id,
)
if tab == "unread":
stmt = stmt.where(
Notification.is_read.is_(False),
Notification.is_archived.is_(False),
)
elif tab == "archive":
stmt = stmt.where(Notification.is_archived.is_(True))
else:
stmt = stmt.where(Notification.is_archived.is_(False))
if category:
stmt = stmt.where(Notification.category == category)
return stmt.order_by(Notification.created_at.desc())
Unread counts should use the same definition as the unread list:
stmt = select(func.count()).where(
Notification.user_id == user_id,
Notification.organization_id == organization_id,
Notification.is_read.is_(False),
Notification.is_archived.is_(False),
)
Cursor pagination keeps list requests small as notification history grows. The FastAPI route uses CursorPage; the frontend should read its next_page field to request the next page.
3. Create notifications from domain services
Business services know when an event matters. They call the notification service rather than coupling domain logic to Redis channel names or serialization.
await notification_service.create_notification(
NotificationCreate(
user_id=trip.created_by_id,
organization_id=organization_id,
title="Trip allocated",
body=f"Trip {trip.transaction_number} was allocated.",
category=NotificationCategory.TRIPS,
meta={"trip_id": str(trip.id)},
),
redis=redis,
)
The notification service persists via the repository and then publishes a JSON-safe representation:
notification = await self.repo.create(payload)
event_data = NotificationResponse.model_validate(
notification,
from_attributes=True,
).model_dump(mode="json")
await publish_notification(
redis,
payload.organization_id,
payload.user_id,
{"event_type": "notification", **event_data},
)
The attached implementation publishes during the request while the request-scoped database session is still open. The repository flushes the insert, and the request dependency commits later. This means Redis can deliver an event before the database transaction commits. An immediate history refetch can race that commit, too. For a small system, refetch with a small delay/retry or accept eventual UI refresh; do not claim that the event and database commit are atomic.
For stronger consistency, write an outbox row in the same transaction as the notification. A worker can publish committed outbox records and retry failures. That is a reliability upgrade, not a feature Redis Pub/Sub provides by itself.
4. Publish and subscribe on user-scoped channels
Use organization and user IDs in channel names:
channel = f"notifications:{organization_id}:{user_id}"
await redis.publish(channel, json.dumps(event_data))
Unread-count changes can use a separate channel:
channel = f"notifications:count:{organization_id}:{user_id}"
await redis.publish(channel, json.dumps({"unread_count": count}))
Do not let clients choose these IDs. Derive the user and active organization from the authenticated request, and only subscribe the server-side stream to those values.
5. Encode real SSE events correctly
SSE has a wire format with named events, data, and optional comments. With sse-starlette, yield ServerSentEvent objects (or supported event dictionaries), not strings that already contain event: and data: lines. A plain string is encoded as an SSE data: value; wrapping preformatted SSE text as a string does not preserve it as event framing.
import asyncio
import json
from redis.asyncio import Redis
from sse_starlette.sse import ServerSentEvent
async def notification_stream(
redis: Redis,
user_id: UUID,
organization_id: UUID,
initial_count: int,
):
channel = f"notifications:{organization_id}:{user_id}"
pubsub = redis.pubsub()
try:
await pubsub.subscribe(channel)
yield ServerSentEvent(
event="connected",
data=json.dumps({"unread_count": initial_count}),
)
while True:
try:
message = await asyncio.wait_for(
pubsub.get_message(ignore_subscribe_messages=True),
timeout=15,
)
except TimeoutError:
yield ServerSentEvent(comment="heartbeat")
continue
if message and message["type"] == "message":
payload = json.loads(message["data"])
event_name = payload.pop("event_type", "notification")
yield ServerSentEvent(
event=event_name,
data=json.dumps(payload),
)
finally:
await pubsub.unsubscribe(channel)
await pubsub.aclose()
The timeout is handled inside the loop so heartbeats continue while the stream is idle. Also retain cancellation handling and cleanup; an SSE connection can live much longer than an ordinary request.
The route returns the stream using EventSourceResponse:
ActiveMemberDep = Annotated[
OrganizationMember,
Depends(resolve_active_member),
]
CurrentUserDep = Annotated[
UserResponseSchema,
Depends(get_current_active_user),
]
DbSessionDep = Annotated[
AsyncSession,
Depends(get_db_session, scope="function"),
]
RedisDep = Annotated[Redis, Depends(get_redis_from_request)]
@router.get("/stream")
async def stream_notifications(
member: ActiveMemberDep,
current_user: CurrentUserDep,
db: DbSessionDep,
redis: RedisDep,
):
initial_count = await notification_service(db).get_unread_count(
current_user.id,
member.organization_id,
)
events = notification_stream(
redis,
current_user.id,
member.organization_id,
initial_count,
)
return EventSourceResponse(events)
Authentication and active-membership resolution happen before returning the stream. The stream’s Redis subscription is then scoped to that authenticated user and organization.
6. Expose history and state-changing endpoints
A small API usually needs:
| Method | Path | Purpose |
|---|---|---|
GET |
/v1/notifications?tab=all&size=10 |
Cursor-paginated history |
GET |
/v1/notifications/unread-count |
Current unread count |
GET |
/v1/notifications/stream |
Named SSE events |
PATCH |
/v1/notifications/{id}/read |
Mark one as read |
PATCH |
/v1/notifications/mark-all-read |
Mark visible unread notifications as read |
PATCH |
/v1/notifications/{id}/archive |
Archive one notification |
DELETE |
/v1/notifications/{id} |
Delete one notification |
Use UUID path parameters in the backend. In the example application, the notification router is mounted under /query/api/v1/notifications; the frontend reaches the upstream service through its /api Next.js proxy. Confirm your deployment’s proxy/base URL instead of copying a path without checking it.
Complete backend reference implementation
The snippets above explain the individual responsibilities. The file-shaped
examples below connect them into a working backend: schemas, repository,
service, Redis/SSE stream, and router. They use this article's example package
layout; change every src.app... and src.core... import to match your own
project's folders and module names. In particular, replace the example
authentication, active-membership, database-session, and Redis dependencies
with your application's equivalents. Never accept user_id or
organization_id from an untrusted request body for these endpoints.
schemas.py
from datetime import datetime
from typing import Any
from uuid import UUID
from pydantic import BaseModel, ConfigDict
# Change this project import to match your package and module path.
from src.app.shared.enums import NotificationCategory
class NotificationResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: UUID
organization_id: UUID
user_id: UUID
title: str
body: str | None
category: NotificationCategory
action_url: str | None
meta: dict[str, Any] | None
is_read: bool
is_archived: bool
created_at: datetime
class NotificationCreate(BaseModel):
user_id: UUID
organization_id: UUID
title: str
body: str | None = None
category: NotificationCategory = NotificationCategory.SYSTEM
action_url: str | None = None
meta: dict[str, Any] | None = None
class NotificationSingleResponse(BaseModel):
message: str
data: NotificationResponse
status: int
class UnreadCountData(BaseModel):
unread_count: int
class UnreadCountResponse(BaseModel):
message: str
data: UnreadCountData
status: int
class NotificationActionResponse(BaseModel):
message: str
status: int
NotificationCreate is an internal service input in this example. If you also
allow clients to create notifications, define a separate request schema that
does not expose the recipient IDs; derive those from the authenticated user and
active organization instead.
repository.py
All reads and writes are scoped to both the authenticated user and active
organization. This repository deliberately uses AsyncSession directly so
the database behavior is visible; if your project has a shared repository
base class, you can adapt these methods to it.
from typing import Annotated
from uuid import UUID
from fastapi import Depends
from sqlalchemy import func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
# Change these project imports to match your package and module paths.
from src.app.domains.notification.models import Notification
from src.app.domains.notification.schemas import NotificationCreate
from src.core.db_redis_dependency import get_db_session
class NotificationRepository:
def __init__(self, db: AsyncSession) -> None:
self.db = db
async def create(self, payload: NotificationCreate) -> Notification:
notification = Notification(**payload.model_dump())
self.db.add(notification)
await self.db.flush()
await self.db.refresh(notification)
return notification
def list_query(
self,
user_id: UUID,
organization_id: UUID,
tab: str,
category: str | None,
):
statement = select(Notification).where(
Notification.user_id == user_id,
Notification.organization_id == organization_id,
)
if tab == "unread":
statement = statement.where(
Notification.is_read.is_(False),
Notification.is_archived.is_(False),
)
elif tab == "archive":
statement = statement.where(Notification.is_archived.is_(True))
else:
statement = statement.where(Notification.is_archived.is_(False))
if category is not None:
statement = statement.where(Notification.category == category)
return statement.order_by(
Notification.created_at.desc(),
Notification.id.desc(),
)
async def get_for_user(
self,
notification_id: UUID,
user_id: UUID,
organization_id: UUID,
) -> Notification | None:
result = await self.db.execute(
select(Notification).where(
Notification.id == notification_id,
Notification.user_id == user_id,
Notification.organization_id == organization_id,
)
)
return result.scalar_one_or_none()
async def unread_count(self, user_id: UUID, organization_id: UUID) -> int:
result = await self.db.execute(
select(func.count()).where(
Notification.user_id == user_id,
Notification.organization_id == organization_id,
Notification.is_read.is_(False),
Notification.is_archived.is_(False),
)
)
return result.scalar_one()
async def mark_as_read(self, notification: Notification) -> Notification:
notification.is_read = True
await self.db.flush()
await self.db.refresh(notification)
return notification
async def mark_all_as_read(
self, user_id: UUID, organization_id: UUID
) -> None:
await self.db.execute(
update(Notification)
.where(
Notification.user_id == user_id,
Notification.organization_id == organization_id,
Notification.is_read.is_(False),
Notification.is_archived.is_(False),
)
.values(is_read=True)
)
await self.db.flush()
async def archive(self, notification: Notification) -> Notification:
notification.is_archived = True
notification.is_read = True
await self.db.flush()
await self.db.refresh(notification)
return notification
async def delete(self, notification: Notification) -> None:
await self.db.delete(notification)
await self.db.flush()
def get_notification_repository(
db: Annotated[AsyncSession, Depends(get_db_session, scope="function")],
) -> NotificationRepository:
return NotificationRepository(db)
services.py
The service owns the workflow: it combines repository operations, serialization,
and best-effort Redis publishing. Redis failures are logged and do not undo a
durable database write; other errors are not disguised as successful results.
from collections.abc import Iterable
from typing import Any
from uuid import UUID
from fastapi import HTTPException, status
from fastapi_pagination.cursor import CursorPage, CursorParams
from fastapi_pagination.ext.sqlalchemy import paginate as sqlalchemy_paginate
from loguru import logger
from redis.asyncio import Redis
from sqlalchemy.ext.asyncio import AsyncSession
from src.app.domains.notification.models import Notification
from src.app.domains.notification.records import NotificationStream
from src.app.domains.notification.repository import NotificationRepository
from src.app.domains.notification.schemas import (
NotificationCreate,
NotificationResponse,
NotificationSingleResponse,
)
from src.app.domains.notification.stream import RedisNotificationStreamProvider
from src.app.domains.permissions.repository import PermissionRepository
from src.app.shared.enums import NotificationCategory
from src.utils.redis import publish_notification, publish_unread_count
class NotificationService:
def __init__(self, db: AsyncSession, repo: NotificationRepository) -> None:
self.db = db
self.repo = repo
def _to_response(self, notifs: Notification) -> NotificationResponse:
return NotificationResponse.model_validate(notifs, from_attributes=True)
async def list_notifications(
self,
user_id: UUID,
organization_id: UUID,
tab: str,
category: str | None,
params: CursorParams,
) -> CursorPage[NotificationResponse]:
stmt = self.repo.list_query(
user_id=user_id,
organization_id=organization_id,
tab=tab,
category=category,
)
page: CursorPage[Notification] = await sqlalchemy_paginate(
self.db, stmt, params=params
)
page.items = [self._to_response(w) for w in page.items]
return page
async def get_unread_count(self, user_id: UUID, organization_id: UUID) -> int:
return await self.repo.unread_count(user_id, organization_id)
async def create_notification(
self, payload: NotificationCreate, redis: Redis | None = None
) -> Notification:
notif = await self.repo.create(payload)
if redis is not None:
try:
notif_data = {
"event_type": "notification",
**self._to_response(notif).model_dump(mode="json"),
}
await publish_notification(
redis, payload.organization_id, payload.user_id, notif_data
)
except Exception as e:
logger.error(
f"Failed to publish notification to user {payload.user_id}: {e}"
)
return notif
async def update_notification_metadata(
self,
user_id: UUID,
organization_id: UUID,
notification_id: UUID,
meta: dict,
) -> NotificationSingleResponse:
notif = await self.repo.get_for_user_by_id(
notification_id, organization_id, user_id
)
if not notif:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Notification not found",
)
updated_notif = await self.repo.update_metadata(notif, meta)
return self._to_response(updated_notif)
async def mark_as_read(
self,
user_id: UUID,
organization_id: UUID,
notification_id: UUID,
redis: Redis | None = None,
) -> NotificationSingleResponse:
notif = await self.repo.get_for_user_by_id(
notification_id, organization_id, user_id
)
if not notif:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Notification not found",
)
if notif.is_read:
return self._to_response(notif)
updated_notif = await self.repo.mark_as_read(notif)
if redis is not None:
try:
count = await self.repo.unread_count(user_id, organization_id)
await publish_unread_count(redis, organization_id, user_id, count)
except Exception:
pass
return self._to_response(updated_notif)
async def mark_all_as_read(
self, user_id: UUID, organization_id: UUID, redis: Redis | None = None
) -> None:
await self.repo.mark_all_as_read(user_id, organization_id)
if redis is not None:
try:
count = await self.repo.unread_count(user_id, organization_id)
await publish_unread_count(redis, organization_id, user_id, count)
except Exception:
pass
async def archive_notification(
self,
user_id: UUID,
organization_id: UUID,
notification_id: UUID,
redis: Redis | None = None,
) -> NotificationSingleResponse:
notif = await self.repo.get_for_user_by_id(
notification_id, organization_id, user_id
)
if not notif:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Notification not found",
)
if notif.is_archived:
return self._to_response(notif)
was_unread = not notif.is_read
updated_notif = await self.repo.archive(notif)
# Archiving also marks it read, so the unread count drops.
if was_unread and redis is not None:
try:
count = await self.repo.unread_count(user_id, organization_id)
await publish_unread_count(redis, organization_id, user_id, count)
except Exception:
pass
return self._to_response(updated_notif)
async def delete_notification(
self,
user_id: UUID,
organization_id: UUID,
notification_id: UUID,
redis: Redis | None = None,
) -> bool:
notif = await self.repo.get_for_user_by_id(
notification_id, organization_id, user_id
)
if not notif:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Notification not found",
)
deleted = await self.repo.delete_notification(
notification_id, user_id, organization_id
)
if deleted and redis is not None:
try:
count = await self.repo.unread_count(user_id, organization_id)
await publish_unread_count(redis, organization_id, user_id, count)
except Exception:
pass
return deleted
async def open_notification_stream(
self, user_id: UUID, organization_id: UUID, redis: Redis
) -> NotificationStream:
initial_count = await self.repo.unread_count(user_id, organization_id)
stream = RedisNotificationStreamProvider()
get_events = stream.stream_notifications(
redis=redis,
user_id=user_id,
organization_id=organization_id,
initial_count=initial_count,
)
return NotificationStream(events=get_events, initial_count=initial_count)
async def open_unread_count_stream(
self, user_id: UUID, organization_id: UUID, redis: Redis
) -> NotificationStream:
initial_count = await self.repo.unread_count(user_id, organization_id)
stream = RedisNotificationStreamProvider()
get_events = stream.stream_unread_count(
redis=redis,
user_id=user_id,
organization_id=organization_id,
initial_count=initial_count,
)
return NotificationStream(events=get_events, initial_count=initial_count)
def notification_service(db: AsyncSession) -> NotificationService:
return NotificationService(db, NotificationRepository(db))
Call create_notification from the domain service that owns the business
event. get_notification_service is a small factory; wire it through your
usual dependency provider if your application uses one.
stream.py
These methods are synchronous; they return an async generator.
from uuid import UUID
from redis.asyncio import Redis
# Use your folder imports
from src.utils.redis import notification_streamer, unread_count_streamer
class RedisNotificationStreamProvider:
# These methods are synchronous; they return the async generator object.
def stream_notifications(
self, *, redis: Redis, user_id: UUID, organization_id: UUID, initial_count: int
):
return notification_streamer(redis, user_id, organization_id, initial_count)
def stream_unread_count(
self, *, redis: Redis, user_id: UUID, organization_id: UUID, initial_count: int
):
return unread_count_streamer(redis, user_id, organization_id, initial_count)
redis.py
EventSourceResponse frames the event itself.
import asyncio
import json
from typing import Any
from uuid import UUID
from loguru import logger
from redis.asyncio import Redis
from redis.asyncio.client import PubSub
from sse_starlette.event import ServerSentEvent
# Heartbeat interval in seconds
HEARTBEAT_INTERVAL = 15
def _sse(event: str, data: dict[str, Any]) -> ServerSentEvent:
# EventSourceResponse frames the event itself; a pre-formatted string would
# be wrapped again as `data:` and lose its event name.
return ServerSentEvent(data=json.dumps(data), event=event)
async def _next_message(pubsub: PubSub) -> dict[str, Any] | None:
# Without a timeout get_message returns at once and the stream loop spins.
message = await pubsub.get_message(
ignore_subscribe_messages=True, timeout=HEARTBEAT_INTERVAL
)
if message is None or message["type"] != "message":
return None
return json.loads(message["data"])
async def notification_streamer(
redis: Redis,
user_id: UUID,
organization_id: UUID,
initial_count: int = 0,
):
"""
SSE stream generator for real-time notifications.
Subscribes to a user-specific Redis channel and yields notifications
as SSE events. Includes heartbeat to keep connection alive.
Args:
user_id: The UUID of the user to stream notifications for
initial_count: The initial unread count to send on connection
Yields:
Named server-sent events with notification data, or heartbeat comments
"""
pubsub = redis.pubsub()
channel = f"notifications:{organization_id}:{user_id}"
try:
await pubsub.subscribe(channel)
logger.info(f"SSE notification stream established for user {user_id}")
yield _sse(
"connected",
{
"status": "connected",
"user_id": str(user_id),
"unread_count": initial_count,
},
)
while True:
event_data = await _next_message(pubsub)
if event_data is None:
yield ServerSentEvent(comment="heartbeat")
continue
yield _sse(event_data.get("event_type", "notification"), event_data)
except asyncio.CancelledError:
logger.info(f"SSE notification stream cancelled for user {user_id}")
raise
except Exception as e:
logger.error(f"SSE notification stream error for user {user_id}: {e}")
yield _sse("error", {"error": "stream_error"})
finally:
try:
await pubsub.unsubscribe(channel)
await pubsub.close()
except Exception as e:
logger.warning(f"Error closing notification pubsub for user {user_id}: {e}")
async def unread_count_streamer(
redis: Redis,
user_id: UUID,
organization_id: UUID,
initial_count: int = 0,
):
"""
SSE stream generator specifically for unread count updates.
This is a lightweight stream that only sends unread count updates,
ideal for displaying notification badges that need instant updates.
Args:
user_id: The UUID of the user to stream count for
initial_count: The initial unread count from database
Yields:
Named server-sent events with count data, or heartbeat comments
"""
pubsub = redis.pubsub()
channel = f"notifications:count:{organization_id}:{user_id}"
try:
await pubsub.subscribe(channel)
logger.info(f"SSE unread count stream established for user {user_id}")
yield _sse("count", {"unread_count": initial_count})
while True:
count_data = await _next_message(pubsub)
if count_data is None:
yield ServerSentEvent(comment="heartbeat")
continue
yield _sse("count", count_data)
except asyncio.CancelledError:
logger.info(f"SSE unread count stream cancelled for user {user_id}")
raise
except Exception as e:
logger.error(f"SSE unread count stream error for user {user_id}: {e}")
yield _sse("error", {"error": "stream_error"})
finally:
try:
await pubsub.unsubscribe(channel)
await pubsub.close()
except Exception as e:
logger.warning(f"Error closing count pubsub for user {user_id}: {e}")
async def publish_notification(
redis: Redis,
organization_id: UUID,
user_id: UUID,
notification_data: dict,
):
"""
Publish a notification to a user's Redis channel.
Args:
user_id: The UUID of the user to notify
notification_data: Dictionary containing notification data
Returns:
int: Number of subscribers that received the message
"""
channel = f"notifications:{organization_id}:{user_id}"
try:
result = await redis.publish(channel, json.dumps(notification_data))
logger.info(
f"Published notification to {channel}, {result} subscribers received"
)
return result
except Exception as e:
logger.error(f"Failed to publish notification to {channel}: {e}")
raise
async def publish_unread_count(
redis: Redis, organization_id: UUID, user_id: UUID, count: int
):
"""
Publish an unread count update to both notification and count channels.
Publishes to:
- notifications:{organization_id}:{user_id} - main notification stream
- notifications:count:{organization_id}:{user_id} - unread count stream
Args:
user_id: The UUID of the user to notify
count: The new unread notification count
Returns:
int: Total number of subscribers that received the message
"""
count_data = {"event_type": "unread_count", "unread_count": count}
try:
# Publish to both channels
notification_channel = f"notifications:{organization_id}:{user_id}"
count_channel = f"notifications:count:{organization_id}:{user_id}"
result1 = await redis.publish(notification_channel, json.dumps(count_data))
result2 = await redis.publish(count_channel, json.dumps(count_data))
logger.info(f"Published unread count {count} to user {user_id}")
return result1 + result2
except Exception as e:
logger.error(f"Failed to publish unread count for user {user_id}: {e}")
raise
router.py
The example assumes resolve_active_member proves the authenticated user
belongs to the active organization, while get_current_active_user returns
the authenticated user. Adapt those dependencies and the UserResponseSchema
import to your application. The client never supplies the recipient or tenant
identity.
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, Query, status
from fastapi_pagination.cursor import CursorPage, CursorParams
from redis.asyncio import Redis
from sqlalchemy.ext.asyncio import AsyncSession
from sse_starlette.sse import EventSourceResponse
# Change these project imports and dependency paths to match your application.
from src.app.auth.schemas import UserResponseSchema
from src.app.domains.notification.repository import (
NotificationRepository,
get_notification_repository,
)
from src.app.domains.notification.schemas import (
NotificationActionResponse,
NotificationResponse,
NotificationSingleResponse,
UnreadCountResponse,
)
from src.app.domains.notification.services import (
NotificationService,
get_notification_service,
)
from src.app.domains.notification.stream import (
notification_stream,
unread_count_stream,
)
from src.app.domains.organization.models import OrganizationMember
from src.app.shared.enums import NotificationCategory
from src.app.shared.permissions import resolve_active_member
from src.core.db_redis_dependency import (
get_db_session,
get_redis_from_request,
)
from src.utils.user_utils import get_current_active_user
router = APIRouter(
prefix="/query/api/v1/notifications",
tags=["Notifications"],
)
CurrentUser = Annotated[
UserResponseSchema,
Depends(get_current_active_user),
]
ActiveMember = Annotated[
OrganizationMember,
Depends(resolve_active_member),
]
DbSession = Annotated[
AsyncSession,
Depends(get_db_session, scope="function"),
]
RedisClient = Annotated[Redis, Depends(get_redis_from_request)]
NotificationRepo = Annotated[
NotificationRepository,
Depends(get_notification_repository),
]
def get_notification_service(
notification_repo: NotificationRepo,
db: DbSession,
) -> NotificationService:
return NotificationService(
db=db,
repository=notification_repo,
)
@router.get("", status_code=status.HTTP_200_OK)
async def list_notifications(
current_user: CurrentUser,
member: ActiveMember,
get_notification_service: NotificationService,
params: Annotated[CursorParams, Depends()],
tab: Annotated[str, Query(pattern="^(all|unread|archive)$")] = "all",
category: Annotated[NotificationCategory | None, Query()] = None,
) -> CursorPage[NotificationResponse]:
return await get_notification_service.list_notifications(
user_id=current_user.id,
organization_id=member.organization_id,
tab=tab,
category=category,
params=params,
)
@router.get("/unread-count", status_code=status.HTTP_200_OK)
async def get_unread_count(
current_user: CurrentUser,
member: ActiveMember,
get_notification_service: NotificationService,
) -> UnreadCountResponse:
count = await get_notification_service.get_unread_count(
current_user.id,
member.organization_id,
)
return {
"message": "Unread notifications count retrieved",
"data": {"unread_count": count},
"status": status.HTTP_200_OK,
}
@router.get("/stream", status_code=status.HTTP_200_OK,)
async def stream_notifications(
current_user: CurrentUser,
member: ActiveMember,
get_notification_service: NotificationService,
redis: RedisClient,
) -> EventSourceResponse:
count = await get_notification_service.get_unread_count(
current_user.id,
member.organization_id,
)
return EventSourceResponse(
notification_stream(
redis,
current_user.id,
member.organization_id,
count,
),
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
@router.get("/unread-count/stream", status_code=status.HTTP_200_OK,)
async def stream_unread_count(
current_user: CurrentUser,
member: ActiveMember,
get_notification_service: NotificationService,
redis: RedisClient,
) -> EventSourceResponse:
count = await get_notification_service.get_unread_count(
current_user.id,
member.organization_id,
)
return EventSourceResponse(
unread_count_stream(
redis,
current_user.id,
member.organization_id,
count,
),
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
@router.patch(
"/{notification_id}/read",
status_code=status.HTTP_200_OK,
)
async def mark_notification_read(
notification_id: UUID,
current_user: CurrentUser,
member: ActiveMember,
get_notification_service: NotificationService,
redis: RedisClient,
) -> NotificationSingleResponse:
notification = await get_notification_service.mark_as_read(
notification_id,
current_user.id,
member.organization_id,
redis,
)
return {
"message": "Notification marked as read",
"data": notification,
"status": status.HTTP_200_OK,
}
@router.patch("/mark-all-read", status_code=status.HTTP_200_OK,)
async def mark_all_notifications_read(
current_user: CurrentUser,
member: ActiveMember,
get_notification_service: NotificationService,
redis: RedisClient,
) -> NotificationActionResponse:
await get_notification_service.mark_all_as_read(
current_user.id,
member.organization_id,
redis,
)
return {
"message": "All notifications marked as read",
"status": status.HTTP_200_OK,
}
@router.patch(
"/{notification_id}/archive",
status_code=status.HTTP_200_OK,
)
async def archive_notification(
notification_id: UUID,
current_user: CurrentUser,
member: ActiveMember,
get_notification_service: NotificationService,
redis: RedisClient,
) -> NotificationSingleResponse:
notification = await get_notification_service.archive(
notification_id,
current_user.id,
member.organization_id,
redis,
)
return {
"message": "Notification archived",
"data": notification,
"status": status.HTTP_200_OK,
}
@router.delete(
"/{notification_id}",
status_code=status.HTTP_204_NO_CONTENT,
)
async def delete_notification(
notification_id: UUID,
current_user: CurrentUser,
member: ActiveMember,
get_notification_service: NotificationService,
redis: RedisClient,
) -> NotificationActionResponse:
await get_notification_service.delete(
notification_id,
current_user.id,
member.organization_id,
redis,
)
return {
"message": "Notification deleted",
"status": status.HTTP_200_OK,
}
Finally, mount the router in your FastAPI application (change the import to
your module path):
# Change this import to the router module path in your application.
from src.app.domains.notification.router import router as notifications_router
app.include_router(notifications_router)
The database dependency should commit after successful requests and roll back
on errors. Redis publication here is best effort and occurs before that commit,
so a connected client can receive an event slightly before a history refetch
can see its row. Use a transactional outbox if publication must happen only
after commit and be retried durably.
Frontend: make the API contract explicit
The attached frontend types and component use pkid: number, next_cursor, and category names such as BOOKING and SCHEDULING. The backend returns id: UUID, cursor-page fields including next_page, and categories such as TRIPS, EXPENSES, and PAYMENTS. These contracts need to match or be translated at one explicit boundary.
For the API shown above, define the frontend types from the backend contract:
export type NotificationCategory =
| "SYSTEM"
| "COMMUNICATION"
| "ADMINISTRATIVE"
| "PAYMENTS"
| "EXPENSES"
| "TRIPS";
export type NotificationTab = "all" | "unread" | "archive";
export interface Notification {
id: string; // UUID serialized as a string
organization_id: string;
user_id: string;
title: string;
body: string | null;
category: NotificationCategory;
action_url: string | null;
meta: Record<string, unknown> | null;
is_read: boolean;
is_archived: boolean;
created_at: string;
}
export interface NotificationPage {
items: Notification[];
next_page: string | null;
previous_page: string | null;
total: number;
}
Use id consistently for React keys, mutation variables, cache matching, and API routes. If an older frontend needs a numeric pkid, build and test an adapter; do not silently assume the backend UUID can be used as a number.
1. Query history and unread count
The frontend API functions call the durable endpoints. getNextPageParam must match the backend cursor response:
export const useInfiniteNotifications = ({
tab,
category,
}: {
tab: NotificationTab;
category?: NotificationCategory;
}) =>
useInfiniteQuery({
queryKey: ["notifications", { tab, category }],
initialPageParam: null as string | null,
queryFn: ({ pageParam }) =>
get<NotificationPage>("/v1/notifications", {
params: {
tab,
category,
size: 10,
cursor: pageParam,
},
}),
getNextPageParam: (lastPage) => lastPage.next_page ?? undefined,
});
The unread count is a separate query so the badge can be updated independently:
export const useNotificationUnreadCount = () =>
useQuery({
queryKey: ["notifications", "unread-count"],
queryFn: () =>
get<{ data: { unread_count: number }; status: number }>(
"/v1/notifications/unread-count"
),
staleTime: 30_000,
retry: false,
});
The current Next.js fetcher sends requests to a same-origin /api/... route, which forwards cookies upstream. Use that same origin for SSE when possible:
const source = new EventSource("/api/v1/notifications/stream", {
withCredentials: true,
});
This avoids hard-coding a backend host in a client component. For direct cross-origin SSE, configure CORS and cookie attributes deliberately, and use the correct upstream base path (the backend router is mounted beneath /query/api in this application).
2. Listen for named events—not only onmessage
The backend sends named SSE events: connected, notification, and unread_count. Browser EventSource.onmessage handles only unnamed message events. Register listeners for each custom event:
useEffect(() => {
const source = new EventSource("/api/v1/notifications/stream", {
withCredentials: true,
});
const onConnected = (event: Event) => {
const data = JSON.parse((event as MessageEvent<string>).data) as {
unread_count: number;
};
queryClient.setQueryData(UNREAD_COUNT_QUERY_KEY, (old: UnreadCount | undefined) =>
old
? { ...old, data: { unread_count: data.unread_count } }
: { data: { unread_count: data.unread_count }, status: 200 }
);
};
const onNotification = (_event: Event) => {
// History is durable; refetch it instead of trusting a transient event
// to maintain cursor pages and every active tab/category filter.
void queryClient.invalidateQueries({ queryKey: ["notifications"] });
void queryClient.invalidateQueries({ queryKey: UNREAD_COUNT_QUERY_KEY });
};
const onUnreadCount = (event: Event) => {
const data = JSON.parse((event as MessageEvent<string>).data) as {
unread_count: number;
};
queryClient.setQueryData(UNREAD_COUNT_QUERY_KEY, (old: UnreadCount | undefined) =>
old
? { ...old, data: { unread_count: data.unread_count } }
: { data: { unread_count: data.unread_count }, status: 200 }
);
};
source.addEventListener("connected", onConnected);
source.addEventListener("notification", onNotification);
source.addEventListener("unread_count", onUnreadCount);
source.onerror = () => {
// EventSource retries automatically unless the connection is closed.
// Keep the durable list endpoint as the recovery path.
};
return () => {
source.removeEventListener("connected", onConnected);
source.removeEventListener("notification", onNotification);
source.removeEventListener("unread_count", onUnreadCount);
source.close();
};
}, [queryClient]);
The important correction is addEventListener. If the server sets event: notification, that event will not arrive through source.onmessage.
Invalidating the list on a notification event is intentionally conservative. Prepending into every cached cursor page can put items into the wrong tab, category, or page. If you choose to update the cache directly for a snappier UI, deduplicate by id and update only query keys whose filters match the event.
3. Make read/archive/delete actions optimistic
TanStack Query mutations can update the UI before the server responds. The safe pattern is:
- Cancel queries that could overwrite the optimistic change.
- Snapshot the affected caches.
- Apply the change.
- Restore the snapshots if the mutation fails.
- Invalidate the queries after settlement.
For example, mark-read mutations should accept the backend UUID:
import {
InfiniteData,
QueryKey,
useMutation,
useQueryClient,
} from "@tanstack/react-query";
import { ApiError, patch } from "@/lib/fetcher";
type UnreadCount = {
data: { unread_count: number };
status: number;
};
const UNREAD_COUNT_QUERY_KEY = ["notifications", "unread-count"] as const;
type NotificationMutationContext = {
lists: Array<[QueryKey, InfiniteData<NotificationPage> | undefined]>;
unreadCount: UnreadCount | undefined;
};
const markRead = (id: string) =>
patch<void>(`/v1/notifications/${id}/read`, {});
const useMarkNotificationRead = () => {
const queryClient = useQueryClient();
return useMutation<void, ApiError, string, NotificationMutationContext>({
mutationFn: markRead,
onMutate: async (id) => {
await queryClient.cancelQueries({ queryKey: ["notifications"] });
await queryClient.cancelQueries({ queryKey: UNREAD_COUNT_QUERY_KEY });
const lists = queryClient.getQueriesData<InfiniteData<NotificationPage>>({
queryKey: ["notifications"],
});
const unreadCount =
queryClient.getQueryData<UnreadCount>(UNREAD_COUNT_QUERY_KEY);
const target = lists
.flatMap(([, data]) => data?.pages.flatMap((page) => page.items) ?? [])
.find((item) => item.id === id);
// Snapshot first. Then update matching items by their UUID.
for (const [queryKey, data] of lists) {
if (!data) continue;
const tab = (queryKey[1] as { tab?: NotificationTab } | undefined)?.tab;
queryClient.setQueryData<InfiniteData<NotificationPage>>(
queryKey,
{
...data,
pages: data.pages.map((page) => ({
...page,
items:
tab === "unread"
? page.items.filter((item) => item.id !== id)
: page.items.map((item) =>
item.id === id ? { ...item, is_read: true } : item
),
})),
}
);
}
if (target && !target.is_read) {
queryClient.setQueryData<UnreadCount>(
UNREAD_COUNT_QUERY_KEY,
(old) =>
old
? {
...old,
data: {
unread_count: Math.max(0, old.data.unread_count - 1),
},
}
: old
);
}
return { lists, unreadCount };
},
onError: (_error, _id, context) => {
context?.lists.forEach(([queryKey, data]) =>
queryClient.setQueryData(queryKey, data)
);
if (context?.unreadCount) {
queryClient.setQueryData(
UNREAD_COUNT_QUERY_KEY,
context.unreadCount
);
}
},
onSettled: async () => {
await queryClient.invalidateQueries({ queryKey: ["notifications"] });
await queryClient.invalidateQueries({
queryKey: UNREAD_COUNT_QUERY_KEY,
});
},
});
};
For a real implementation, decrement the cached unread count only when the target item was unread, and remove it from an unread-only list. The attached mutation hooks already use this snapshot/rollback pattern; the key contract correction is changing their identifier from numeric pkid to string id.
Archiving marks a notification as read in the backend. Ensure the unread count is updated for other connected clients too: publish a fresh count after archive, or have the client invalidate/refetch its count. The backend should be the source of truth for that count.
Where background tasks fit
Despite the common “background task” framing, this implementation does not use FastAPI BackgroundTasks for notification delivery. It stores a notification and publishes the Redis message during the request.
That is deliberate for a simple first version: the notification record is part of the application workflow, and the live publish is a small operation. FastAPI background tasks run in the API process after the response; they are not a durable queue. A process restart can lose pending work, and sharing a request-scoped SQLAlchemy session with a task is unsafe.
If email, push delivery, retries, or high-volume fan-out become requirements, use a durable worker pattern. A transactional outbox is a practical next step:
- Save the notification and an outbox event in one database transaction.
- A worker claims undelivered outbox rows.
- The worker publishes and retries failures.
- Mark events delivered idempotently.
Use a task queue when you need durable execution, controlled concurrency, retries, or scheduling—not just because a task happens after a request.
Operational and security checklist
- Derive the user and organization from authenticated dependencies, not request payloads.
- Scope every notification query and mutation by notification ID, user ID, and organization ID.
- Keep Redis channels user- and organization-specific.
- Validate category values and bound cursor page sizes.
- Treat Redis delivery as best effort; retrieve durable history from PostgreSQL.
- Close Redis Pub/Sub subscriptions when clients disconnect.
- Send heartbeats and configure reverse proxies not to buffer the SSE response.
- Avoid logging notification bodies or sensitive metadata.
- Set CORS and cookie settings deliberately for cross-origin EventSource connections.
- Monitor Redis connection health; application startup may succeed in degraded mode, but live delivery will not be available until Redis recovers.
- For reliable publishing after database commit, use an outbox rather than assuming a database flush is a commit.
Integration gaps in the original attached implementation
If you are adapting the original attached files rather than the complete
reference modules above, close these gaps. The complete backend examples above
already frame SSE events correctly and publish unread-count changes after
archive operations.
The backend and frontend snippets show the intended architecture, but the attached files currently have contract differences worth fixing:
-
SSE framing: the backend generator yields preformatted strings and passes them to
EventSourceResponse.sse-starletteencodes ordinary strings asdata:values. YieldServerSentEventobjects or event dictionaries for custom event names. -
Named SSE handlers: The frontend uses
source.onmessage, while the backend names events. UseaddEventListener("notification", ...)and the matching listeners forconnectedandunread_count. -
Identifiers: the backend exposes UUID
id; the frontend types and mutations use numericpkid. Use the UUID string consistently. -
Cursor fields: the backend cursor page exposes
next_page; the frontend query currently readsnext_cursor. Read the actualCursorPagefield. -
Categories: align frontend category unions and UI labels with the backend values (
SYSTEM,COMMUNICATION,ADMINISTRATIVE,PAYMENTS,EXPENSES, andTRIPS). - Unread count after archive: archiving marks the record read, so also publish the updated count or refetch it.
- Transaction ordering: Redis publication currently occurs before the request-scoped database transaction commits. Treat the event as a hint and refetch, or add a transactional outbox for reliable ordering.
These are not reasons to abandon the design. They are exactly the sorts of details an explicit end-to-end contract makes easier to spot.
Closing
A small notification system can be built from familiar pieces: store user-visible history in PostgreSQL, publish live hints through Redis Pub/Sub, stream them with SSE, and let TanStack Query manage the browser cache.
The simple design works best when its guarantees are stated honestly. Redis Pub/Sub is not durable, SSE is one-way, and a live event should not replace the history API. Align the event names, IDs, pagination fields, and categories across the backend and frontend; then add an outbox or worker only when delivery requirements justify the extra machinery.

Top comments (0)