DEV Community

静亭雅苑
静亭雅苑

Posted on Originally published at wuhuajin.com

A SQLite Outbox for Reliable Email and Chat Notifications

A SQLite Outbox for Reliable Email and Chat Notifications

When a small site needs to notify someone—a new membership application, a support payment, a review result—the tempting implementation is a direct call inside the request handler:

await saveRecord();
await sendEmail();
await sendChatMessage();
res.json({ ok: true });
Enter fullscreen mode Exit fullscreen mode

It works in the happy path and fails in every interesting one. The email provider times out. The chat webhook is rate-limited. The process crashes after the database commit but before the message is sent. The user sees a success page, and the notification is gone.

On wuhuajin.com, I replaced that pattern with a SQLite-backed outbox. The design is small enough for a single-server API, but it gives the site the properties it actually needs: no lost events, bounded retries, and duplicate suppression.


The contract

The outbox is based on one rule:

The database transaction that changes the business state also inserts the notification intent.

If the application row is committed, the notification event is committed. If the transaction rolls back, neither exists. The actual sending happens later, outside the request.

This is the transactional outbox pattern. It is usually described with a message broker, but a single SQLite file is enough for a site at this scale.

The flow:

  1. API writes the business row and an outbox row in one transaction.
  2. A worker claims due outbox rows.
  3. The worker sends the email or chat message.
  4. The worker marks the row as sent, failed, or retrying.
  5. A separate sweeper recovers rows stuck in sending.

The table

CREATE TABLE notification_outbox (
  id             INTEGER PRIMARY KEY AUTOINCREMENT,
  event_type     TEXT NOT NULL,
  channel        TEXT NOT NULL,
  payload        TEXT NOT NULL,
  dedupe_key     TEXT NOT NULL,
  status         TEXT NOT NULL DEFAULT 'pending',
  attempts       INTEGER NOT NULL DEFAULT 0,
  next_attempt_at TEXT NOT NULL,
  last_error     TEXT,
  created_at     TEXT NOT NULL,
  sent_at        TEXT,
  UNIQUE (dedupe_key)
);

CREATE INDEX idx_outbox_due
  ON notification_outbox (status, next_attempt_at);
Enter fullscreen mode Exit fullscreen mode

The fields that matter:

  • event_type: what happened, such as application.created or application.approved.
  • channel: email or chat.
  • payload: a JSON blob with the data needed to render the message. It should not contain secrets.
  • dedupe_key: a stable identity for the event and channel.
  • status: pending, sending, sent, failed, or dead.
  • attempts: how many times delivery has been tried.
  • next_attempt_at: when the row becomes eligible again.
  • last_error: the last failure message, truncated and sanitized.

The unique constraint on dedupe_key is the first line of defense against duplicates. A retry of the same business event cannot create a second row.


Inserting the event

The API uses a transaction:

db.exec('BEGIN IMMEDIATE');
try {
  const application = insertApplication(...);
  insertOutbox({
    event_type: 'application.created',
    channel: 'chat',
    payload: JSON.stringify({ applicationId: application.id }),
    dedupe_key: `application.created:${application.id}:chat`,
    next_attempt_at: now(),
  });
  db.exec('COMMIT');
} catch (err) {
  db.exec('ROLLBACK');
  throw err;
}
Enter fullscreen mode Exit fullscreen mode

BEGIN IMMEDIATE is important in SQLite. It acquires the write lock up front, which avoids a race where two writers both think they can upgrade a deferred transaction.

The payload should contain an application ID, not a full copy of the email and payment details. The worker resolves the current record when it sends. This keeps the outbox small and avoids stale personal data in a queue that may live for days.


Claiming work

A single worker loop is enough for this scale. The claim query selects due rows and marks them sending:

UPDATE notification_outbox
SET status = 'sending',
    attempts = attempts + 1
WHERE id IN (
  SELECT id
  FROM notification_outbox
  WHERE status = 'pending'
    AND next_attempt_at <= ?
  ORDER BY next_attempt_at
  LIMIT 10
)
RETURNING *;
Enter fullscreen mode Exit fullscreen mode

SQLite supports RETURNING, which makes the claim atomic and avoids a separate select-then-update race.

The worker processes one channel at a time. Mixing email and chat in a single batch makes rate limiting harder, because the two providers have different limits and different failure modes.


Rate limiting

The chat webhook is the more sensitive channel. It has a per-minute limit, and exceeding it produces either a hard error or a silent drop, depending on the provider.

The worker uses a simple token bucket per channel:

  • chat: one message every few seconds, with a small burst allowance;
  • email: a fixed number of messages per minute, below the provider’s documented limit.

The rate limiter is not a separate service. It is an in-process gate that checks the time since the last send. Because there is only one worker process, this is sufficient. If the API is ever scaled to multiple workers, the gate must move into the database or a shared queue.

The key behavior is backpressure: when the limit is reached, the worker does not mark the row as failed. It leaves it pending and sets next_attempt_at to the next allowed slot.


Retry and backoff

Failures are classified before retrying:

Failure Retry? Treatment
Network timeout Yes Exponential backoff with jitter
Provider 5xx Yes Retry, then dead-letter
Provider 429 Yes Backoff based on Retry-After if present
Invalid recipient No Mark dead, record reason
Template rendering error No Mark dead, alert
Auth failure No Mark dead, alert; do not loop

The retry schedule is deliberately conservative:

attempt 1: immediate
attempt 2: 1 minute
attempt 3: 5 minutes
attempt 4: 30 minutes
attempt 5: 2 hours
attempt 6: 12 hours
Enter fullscreen mode Exit fullscreen mode

After the maximum attempts, the row moves to dead. A dead row is visible in the admin view and can be replayed manually after the cause is fixed.

Jitter matters. Without it, a provider outage produces a synchronized retry wave when it recovers.


Recovering stuck rows

A process can crash after claiming a row but before marking it sent. Those rows stay in sending forever unless something recovers them.

A sweeper runs every few minutes:

UPDATE notification_outbox
SET status = 'pending',
    next_attempt_at = ?
WHERE status = 'sending'
  AND created_at < ?;
Enter fullscreen mode Exit fullscreen mode

The age threshold must be longer than the maximum expected send time. If it is too short, the sweeper can race a slow but healthy send. If it is too long, recovery is delayed.

The worker also records a sending timestamp. Using created_at alone is not enough for a queue that may process an old event. A dedicated claimed_at column is the cleaner design; I used the existing timestamps for the first version and would add claimed_at before increasing volume.


Deduplication

There are two kinds of duplicates:

  1. Duplicate business events: the same application is inserted twice because the reader double-submits.
  2. Duplicate deliveries: the worker sends the same outbox row twice because the provider timed out after accepting the message.

The unique dedupe_key handles the first kind. The second kind is harder: if the provider accepted the message but the response was lost, a retry can produce a duplicate.

The practical mitigation is:

  • keep the retry window short for chat messages;
  • include a stable event ID in the message body so a human can recognize a duplicate;
  • make the notification idempotent at the application level: “application #123 received” is harmless if repeated once;
  • never use the outbox for a message that must be exactly-once, such as a payment capture.

For email, a duplicate “your application was received” is acceptable. A duplicate “your membership is active” is more annoying, but still better than a lost activation. The design chooses at-least-once delivery with dedupe at the source, not exactly-once.


Observability

A queue without visibility is just a delayed failure. The admin page shows:

  • pending count by channel;
  • oldest pending age;
  • dead count;
  • last error per channel;
  • a manual replay button for dead rows.

The most useful metric is oldest pending age. A large pending count can be normal during a burst. An old pending row means the worker is stuck or the provider is down.

I also log one line per attempt with:

  • outbox ID;
  • event type;
  • channel;
  • attempt number;
  • duration;
  • result.

No email addresses, tokens, or message bodies in the log. The outbox ID is enough to look up the rest in the admin view.


What I deliberately did not build

  • A message broker. For one server and a few events per day, SQLite is simpler and has the same durability guarantee if the database is backed up.
  • Multiple workers. They would require a shared claim protocol and a distributed rate limiter. The current volume does not justify it.
  • A full template engine. The messages are short and have a small number of variants. A function per event type is easier to review.
  • Exactly-once delivery. It is not achievable with typical email and chat providers. At-least-once with dedupe is the honest contract.

The lesson

The important part of this design is not the table schema. It is the boundary:

  • business state and notification intent commit together;
  • delivery is asynchronous and retryable;
  • failures are classified, not blindly retried;
  • duplicates are suppressed at the source;
  • stuck rows are recoverable;
  • the queue is observable.

That boundary turns a fragile “send after save” call into a system that can survive a provider outage, a rate limit, and a process restart.


This article describes the notification outbox used by wuhuajin.com for membership application alerts. The implementation uses SQLite, a single worker, and two channels: transactional email and a team chat webhook.


Originally published on wuhuajin.com.

Top comments (0)