Nov 23, 20267 min read

Build a Notification Service: Channels, Preferences and Delivery

How to route one event to in-app, email and push according to user preferences, deduplicate, keep an unread inbox and retry failed deliveries, with a Go notification service on Encore using Postgres and Pub/Sub.

Illustration for Build a Notification Service: Channels, Preferences and Delivery

Notifications start as a line of code in whatever service has the news. By the fifth kind, users want to turn some off, product wants an in-app unread count, and an email provider outage starts holding up requests that send mail inline.

A dedicated notification service owns who gets what on which channel. This guide covers routing, preferences, deduplication and delivery, and builds the core in Go.

What does a notification service do?

It sits between the services that produce events and the channels that reach people. A producer publishes "user 77 got a reply on comment 4812" and moves on. The notification service decides whether user 77 wants that kind of notification at all and on which channels, writes an in-app entry, and hands off to delivery workers for email and push. Producers never call an email provider, never read preferences and never wait for delivery.

How should preferences be modelled?

As rows of (user_id, kind, channel, enabled), where kind is a stable name such as comment.reply or billing.invoice and channel is in_app, email or push. Missing rows fall back to defaults defined per kind in code, which means new notification kinds ship with sensible behaviour without a backfill. Some kinds, such as security alerts and receipts, should ignore opt-outs for email, since users need them whatever their settings say.

For marketing and digest email, opting out must be easy. Gmail and Yahoo require one-click unsubscribe for bulk senders, as listed in Google's email sender guidelines, so the unsubscribe link should flip the preference row directly without a login.

How do you avoid duplicate and noisy notifications?

Every request carries a deduplication key derived from the event, and the inbox table has a unique constraint on it, so a redelivered event or a producer that retries does nothing the second time. For noisy kinds, collapse rather than repeat: ten likes in a minute should become one "10 people liked your post" entry, which push services support directly through collapse identifiers such as the apns-collapse-id header in Apple's push notification API.

Why give each channel its own queue?

Channels fail independently. The email provider can rate limit you while push works fine, and an in-app entry needs no network call at all. With one delivery queue per channel, each has its own retry policy, concurrency limit and dead-letter handling, and a backlog in one never delays the others. Record delivery attempts per channel so support can answer "did we send it?" without searching logs.

Notification service with Encore

Encore

Encore is a backend framework with built-in infrastructure, so the topics, the subscriptions and the inbox database in this design are declared as Go variables in the notification service. Producers publish to a Pub/Sub topic, the router writes the inbox to an Encore Postgres database and publishes email jobs to a second topic, and the email provider key is an Encore secret. Encore provisions SNS and SQS or Google Cloud Pub/Sub in your own account, so each subscription gets its own queue and retry policy.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- notify/migrations/1_create_notifications.up.sql CREATE TABLE preferences ( user_id TEXT NOT NULL, kind TEXT NOT NULL, channel TEXT NOT NULL CHECK (channel IN ('in_app', 'email', 'push')), enabled BOOLEAN NOT NULL, PRIMARY KEY (user_id, kind, channel) ); CREATE TABLE inbox ( id BIGSERIAL PRIMARY KEY, user_id TEXT NOT NULL, kind TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, dedup_key TEXT NOT NULL UNIQUE, read_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX inbox_user_unread ON inbox (user_id, created_at DESC) WHERE read_at IS NULL;
// notify/notify.go package notify import ( "bytes" "context" "encoding/json" "errors" "fmt" "net/http" "time" "encore.dev/pubsub" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("notify", sqldb.DatabaseConfig{Migrations: "./migrations"}) var secrets struct { ResendAPIKey string } // Request is published by any service that has something to tell a user. type Request struct { UserID string Email string Kind string // for example "comment.reply" Title string Body string DedupKey string // for example "comment.reply:4812:user-77" Mandatory bool // security and billing notices ignore email opt-outs } var Requests = pubsub.NewTopic[*Request]("notification-requests", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type EmailJob struct { To string Subject string Text string Key string } var EmailJobs = pubsub.NewTopic[*EmailJob]("notification-emails", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) // Defaults apply when a user has no preference row for a kind and channel. var defaults = map[string]map[string]bool{ "comment.reply": {"in_app": true, "email": true}, "billing.invoice": {"in_app": true, "email": true}, "post.liked": {"in_app": true, "email": false}, } func enabled(ctx context.Context, r *Request, channel string) (bool, error) { var on bool err := db.QueryRow(ctx, `SELECT enabled FROM preferences WHERE user_id = $1 AND kind = $2 AND channel = $3`, r.UserID, r.Kind, channel).Scan(&on) if errors.Is(err, sqldb.ErrNoRows) { return defaults[r.Kind][channel], nil } return on, err } var _ = pubsub.NewSubscription(Requests, "route-notification", pubsub.SubscriptionConfig[*Request]{ Handler: route, RetryPolicy: &pubsub.RetryPolicy{ MinBackoff: 5 * time.Second, MaxRetries: 10, }, }) func route(ctx context.Context, r *Request) error { inApp, err := enabled(ctx, r, "in_app") if err != nil { return err } // The inbox row commits only after the email job is queued, so a failed publish // rolls back and the retry runs the whole handler again. tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() // The dedup key makes this handler safe to run twice for the same event. res, err := tx.Exec(ctx, `INSERT INTO inbox (user_id, kind, title, body, dedup_key) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (dedup_key) DO NOTHING`, r.UserID, r.Kind, r.Title, r.Body, r.DedupKey) if err != nil { return err } if res.RowsAffected() == 0 { return nil // already handled } if !inApp { // Keep the row for deduplication but leave it out of the unread inbox. if _, err := tx.Exec(ctx, `UPDATE inbox SET read_at = now() WHERE dedup_key = $1`, r.DedupKey); err != nil { return err } } email, err := enabled(ctx, r, "email") if err != nil { return err } if email || r.Mandatory { if _, err := EmailJobs.Publish(ctx, &EmailJob{To: r.Email, Subject: r.Title, Text: r.Body, Key: r.DedupKey}); err != nil { return err } } return tx.Commit() } var _ = pubsub.NewSubscription(EmailJobs, "send-notification-email", pubsub.SubscriptionConfig[*EmailJob]{ Handler: sendEmail, MaxConcurrency: 20, }) func sendEmail(ctx context.Context, j *EmailJob) error { body, _ := json.Marshal(map[string]any{ "from": "Example <notifications@example.com>", "to": j.To, "subject": j.Subject, "text": j.Text, }) req, err := http.NewRequestWithContext(ctx, "POST", "https://api.resend.com/emails", bytes.NewReader(body)) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+secrets.ResendAPIKey) req.Header.Set("Content-Type", "application/json") // The dedup key doubles as the idempotency key, so a repeated job sends one email. req.Header.Set("Idempotency-Key", j.Key) resp, err := http.DefaultClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode >= 300 { return fmt.Errorf("email provider returned %d for %s", resp.StatusCode, j.Key) } return nil } type InboxItem struct { ID int64 Kind string Title string Body string CreatedAt time.Time } type InboxResponse struct { Unread []*InboxItem } // Unread is called by your authenticated API layer with the signed-in user's ID. // //encore:api private method=GET path=/notifications/:userID func Unread(ctx context.Context, userID string) (*InboxResponse, error) { rows, err := db.Query(ctx, `SELECT id, kind, title, body, created_at FROM inbox WHERE user_id = $1 AND read_at IS NULL ORDER BY created_at DESC LIMIT 50`, userID) if err != nil { return nil, err } defer rows.Close() resp := &InboxResponse{} for rows.Next() { it := &InboxItem{} if err := rows.Scan(&it.ID, &it.Kind, &it.Title, &it.Body, &it.CreatedAt); err != nil { return nil, err } resp.Unread = append(resp.Unread, it) } return resp, rows.Err() }

The inbox endpoint is private, so only your own services can call it, and the API layer in front of it passes the user ID from your app's auth handler so each user only ever sees their own notifications. Producers in other services import the topic and publish a Request, and Encore wires the cross-service publish and subscription for you. The email subscription has its own concurrency cap and retries, so a provider outage piles up email jobs while in-app entries keep appearing on time.

encore run starts Postgres and Pub/Sub locally, so you can publish a request from a test endpoint and follow it through routing, the inbox insert and the email job in one trace. Adding push later means one more topic and subscription in this file plus a push default per kind, which a coding agent can add and exercise locally in the same change.

Best fit: Products whose notifications have outgrown inline email calls and need preferences, an in-app inbox and per-channel delivery running in their own cloud account.

Frequently asked questions

How do you design a notification service?

Other services publish a notification event, and the notification service looks up the user's preferences, writes the in-app copy and fans the event out to one delivery queue per channel such as email or push. Each channel retries on its own, so a slow email provider never delays in-app notifications.

How do you stop duplicate notifications?

Give every notification a deduplication key built from the event, such as comment-reply:4812:user-77, and store it with a unique constraint. A retried or replayed event then hits the constraint and is skipped instead of notifying the user twice.

Where should notification preferences be stored?

In the notification service's own database, as rows of user, notification kind, channel and enabled flag, with defaults applied when no row exists. Keeping them there lets the router make every decision with one query and keeps other services free of preference logic.

How do I build a notification service with Encore?

Declare a Pub/Sub topic for notification requests, a subscriber that applies preferences and writes the inbox to an Encore Postgres database, and a second topic and subscriber for email delivery. encore run starts the database and Pub/Sub locally so the whole path can be tested on one machine.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders