Full answer
text
notifications(id, user_id, kind, actor_id, object_type, object_id, payload jsonb,
created_at, read_at, group_key)
CREATE INDEX ON notifications (user_id, created_at DESC);
CREATE INDEX ON notifications (user_id) WHERE read_at IS NULL;- Unread badge:
SELECT COUNT(*) FROM notifications WHERE user_id = :u AND read_at IS NULL, served by the partial index. - Mark all as read:
UPDATE ... SET read_at = now() WHERE user_id = :u AND read_at IS NULL. - Grouping: a
group_keysuch as 'like:post:42' lets the writer update an existing unread row ('Asha and 9 others liked your post') instead of inserting ten. - Retention: keep 90 days, then delete in batches.
Delivery channels (email, push) are a separate concern, usually a queue with per-user preferences in their own table.
Key points
- One row per recipient
- read_at NULL means unread
- Partial index for unread counts
- Group repetitive events
- Apply retention
Common mistakes
- A separate read-receipts table joined on every badge request
- Keeping notifications forever
Follow-ups
- How would you add per-user channel preferences?
- How would you send a notification to a million users?
Tips
- Show the unread query