← Back to SQL, page 20

sql-0400 · Easy fresher

Design storage for in-app notifications with read and unread state.

Store one row per recipient with type, payload, created_at and read_at (NULL while unread). A partial index on (user_id, created_at) WHERE read_at IS NULL makes the unread badge and list fast. Group repetitive events (ten likes) into one notification, and delete or archive old rows on a schedule.

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_key such 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