Notification Subsystem Architecture Map
How templates, triggers, providers, dispatch, delivery, and inbox fit together.
1. Pipeline Overview
Event (gate transition, conversation action)
│
▼
resolve_triggers_for_event(...)
│
▼
NotificationTrigger matching (event_type, role_code, is_active)
│
▼
NotificationTemplate fetch + render (subject, body_html, body_text)
│
▼
resolve_recipients(...) → ResolvedRecipient[]
│
▼
FOR EACH recipient:
create_delivery_row(...) → NotificationDelivery (status='queued')
│
▼
check_dispatch_eligibility(...) ← [queue-time gate]
│
├─ blocked → status='suppressed', suppression_reason='queue_<gate>'
│
└─ passed → stays 'queued'
│
▼
dispatch_pending_notifications(...) [leased-batch worker, every 60s]
│
▼
SELECT … FOR UPDATE SKIP LOCKED (status IN ('queued','failed_transient'))
│
▼
FOR EACH delivery:
rate_limit_acquire(...)
│
▼
NotificationDispatchable.recheck_eligibility() ← [execute-time gate]
│
▼
NotificationDispatchable.execute(...) → provider adapter.send(EmailPayload)
│
▼
classify_error(result)
│
├─ delivered
├─ failed_transient
├─ failed_permanent → on_permanent_failure (flags contact_invalid_flags)
└─ rate_limited
│
▼
UPDATE NotificationDelivery.status
│
▼
Postgres trigger → upserts eapproval_notification_threads
│
▼
InboxService.list_threads / thread_detail / mark_read / mark_unread
2. Data Model
2.1 Core pipeline tables
| Table | Purpose | Key columns |
|---|---|---|
notification_templates | Agency-authored message templates | code, channel, recipient_kind, recipient_config (JSONB), reentrant, requires_acknowledgement |
email_template_bodies | Localised subject + body per template | template_id (1:1), content (JSONB: locale → {subject, body_html, body_text}) |
notification_triggers | Event→template binding per procedure version | event_type, target_role_code, template_id, is_active |
notification_providers | Per-deployment provider registry | deployment_id, channel, connector_code, operation_code, is_active |
notification_deliveries | Dispatch state + inbox source of truth | application_id, trigger_id, template_id, channel, recipient_address, status, classified_error, read_at, is_test |
notification_fire_ledger | Deduplication for non-reentrant templates | (application_id, template_id) |
2.2 Ops / governance tables
| Table | Purpose |
|---|---|
platform_notification_kill_switch | Append-only audit trail of channel on/off flips |
deployment_notification_policy | GDPR legal basis (contractual or consent) per deployment |
deployment_feature_flags | notifications_enabled toggle per deployment |
notification_rate_limits | Postgres-backed counter per (deployment, channel, window) |
notification_consent_events | GDPR Art. 7 demonstrable consent audit |
notification_test_log | PII-redacted audit of admin test sends |
notifications_health_snapshots | Task 10 projection (deployment or procedure scope) |
eapproval_notification_threads | Gmail-style inbox projection (read-optimised) |
2.3 Foreign key graph
notification_templates.procedure_id → smartrules_procedures.id
notification_templates.archived_from_version_id → published_versions.id (archived rows only — M100)
email_template_bodies.template_id → notification_templates.id
notification_triggers.procedure_version_id → published_versions.id
notification_triggers.template_id → notification_templates.id
notification_providers.deployment_id → deployments.id
notification_providers.connector_code → smartlink_connectors.code
notification_deliveries.application_id → eapproval_applications.id
notification_deliveries.trigger_id → notification_triggers.id (SET NULL)
notification_deliveries.template_id → notification_templates.id
notification_fire_ledger.application_id → eapproval_applications.id
notification_fire_ledger.template_id → notification_templates.id
notification_consent_events.application_id → eapproval_applications.id
3. Trigger Evaluation
3.1 Event types
'gate_passed'
'gate_failed'
'convergence_passed'
'all_gates_passed'
'comment_posted'
'clarification_opened'
'clarification_resolved'
'clarification_expired'
'clarification_stale'
3.2 Role consistency rule
| Event type | target_role_code required? |
|---|---|
gate_passed, gate_failed, comment_posted, clarification_opened, clarification_resolved, clarification_expired, clarification_stale | Yes |
convergence_passed, all_gates_passed | No (must be NULL) |
3.3 Call sites
resolve_triggers_for_event(session, application_id, event_type, role_code) is called from:
eapproval/reactions.py— gate transitions:gate_passedon assertgate_failedon recomputeconvergence_passedon convergence activationall_gates_passedon completion
eapproval/conversation/reactions.py— conversation events:comment_postedclarification_opened,clarification_resolved,clarification_expired,clarification_stale
3.4 Resolution query
select(NotificationTrigger).where(
NotificationTrigger.procedure_version_id == app.procedure_version_id,
NotificationTrigger.event_type == event_type,
NotificationTrigger.is_active.is_(True),
NotificationTrigger.target_role_code == role_code # if not None
)
3.5 Non-reentrant dedup
Before fanning out, the dispatcher checks NotificationFireLedger for an existing (application_id, template_id) row. If found and template.reentrant == false, the trigger is skipped.
The ledger is written before inbox rows so a crash mid-loop doesn’t re-evaluate.
4. Provider Selection
4.1 Adapter registry
operation_code follows the convention <provider>:<verb>:
| Prefix | Adapter class |
|---|---|
sendgrid | SendGridEmailAdapter |
smtp | SmtpEmailAdapter |
New adapters register in platform/notifications/providers/registry.py — no schema change required.
4.2 Active provider resolution
select(NotificationProvider).where(
NotificationProvider.deployment_id == deployment.id,
NotificationProvider.channel == delivery.channel,
NotificationProvider.is_active.is_(True),
)
Critical constraint: Partial unique index uq_notification_providers_deployment_channel_active enforces at most one active provider per (deployment, channel). There is no fallback chain.
4.3 Adapter lifecycle
adapter_cls = resolve_adapter(self.provider.operation_code)
adapter = adapter_cls(
connector_code=self.provider.connector_code,
operation_code=self.provider.operation_code,
)
payload = EmailPayload(
to=delivery.recipient_address,
subject=delivery.subject_rendered,
body_html=delivery.body_html_rendered,
body_text=delivery.body_text_rendered,
from_email="noreply@opengov.local",
)
result = await adapter.send(payload)
5. Dispatch Loop
5.1 Entry point
dispatch_pending_notifications(session, batch_size=50) — Procrastinate periodic job, cron * * * * *.
5.2 Concurrency safety
select(NotificationDelivery)
.where(NotificationDelivery.status.in_(["queued", "failed_transient"]))
.limit(batch_size)
.with_for_update(skip_locked=True)
Multiple workers receive disjoint slices via SKIP LOCKED.
5.3 Per-row state machine
- Metrics —
inc_attempted(channel, deployment_code) - Provider lookup — missing →
suppressed/execute_no_provider - Rate-limit gate —
rate_limit_acquire()returnsFalse→failed_transient/rate_limited - Template lookup — missing →
suppressed/execute_no_template - Execute-time eligibility re-check — fails →
suppressed/recheck_<gate> - Status →
attempting— incrementattempt_count, setlast_attempted_at - Execute —
dispatchable.execute(attempt) - Classify result:
success=True→deliveredclassification == "permanent"→failed_permanent; runon_permanent_failureclassification == "rate_limited"→failed_transient/rate_limitedtransient+attempt_count >= MAX_ATTEMPTS→failed_permanent/transient_exhaustedtransient+attempt_count < MAX_ATTEMPTS→failed_transient/transient
- Metrics —
inc_outcome(channel, outcome, deployment_code)
MAX_ATTEMPTS is shared with the integration-event dispatcher (value: 6).
6. Dispatch Eligibility Gates
Eligibility is checked twice: at queue-time (when the delivery row is created) and at execute-time (when the worker picks it up).
| Gate # | Name | Queue-time | Execute-time | Why checked twice |
|---|---|---|---|---|
| 1 | Kill switch | queue_kill_switch | recheck_kill_switch | Admin may flip during backlog |
| 2 | Provider active | queue_no_provider | recheck_no_provider | Provider may be deactivated |
| 3 | Feature flag | queue_feature_flag | recheck_feature_flag | Flag may change |
| 4 | Consent | queue_consent | recheck_consent | Applicant may withdraw |
| 5 | Contact valid | queue_contact_invalid | recheck_contact_invalid | Bounce may flag address |
7. Inbox / Thread Projection
7.1 Source of truth
notification_deliveries is authoritative. eapproval_notification_threads is a read-optimised projection maintained by Postgres triggers (M18).
7.2 Postgres triggers
trg_thread_upsert_on_delivery — AFTER INSERT ON notification_deliveries
WHEN (NEW.is_test = FALSE)- Upserts thread row for
application_id - Sets
last_delivery_at = GREATEST(existing, NEW.created_at) - Clears
archived_at(un-archive on new delivery) - Increments
unread_countwhenNEW.read_at IS NULL
trg_thread_read_transition — AFTER UPDATE OF read_at ON notification_deliveries
WHEN (OLD.is_test = FALSE AND NEW.is_test = FALSE AND OLD.read_at IS DISTINCT FROM NEW.read_at)- Decrements
unread_counton mark-read; increments on mark-unread GREATEST(unread_count - 1, 0)prevents negatives
repair_notification_threads() — stored procedure for disaster recovery
7.3 InboxService
All methods scoped to recipient_sub (Zitadel sub, String 255):
list_threads(recipient_sub, show, date_within, channel)— Gmail-style listing. Joins threads with latest delivery snippet and frozen procedure name frompublished_versions.spec. Filters:active/unread/archived,7d/30d.thread_detail(recipient_sub, application_id)— per-application delivery list, newest first.mark_read(recipient_sub, delivery_id)— dwell-read transition. Refuses if template hasrequires_acknowledgement=TRUE(M20).mark_unread(recipient_sub, delivery_id)— reversal.archive_thread/unarchive_thread— idempotent.
8. Consent / GDPR Art. 7
8.1 Legal basis
deployment_notification_policy declares the basis per deployment:
consent(default if no row) — requires positiveNotificationConsentEventper(application, channel).contractual— bypasses consent checks. CHECK enforcesdpo_signed_off_at IS NOT NULL.
8.2 Consent capture
notification_consent_events is append-only:
| Field | Description |
|---|---|
ui_surface | submission_form, portal_toggle, sms_stop, admin_override, migration_backfill |
granted | bool |
ip | Client IP (INET) |
user_agent | String |
policy_version | Policy version at time of consent |
actor_user_id | Who acted |
CHECK prevents granted=FALSE with ui_surface='submission_form'.
8.3 Consent gate
At eligibility check #4:
if recipient.kind == "applicant_field":
policy = await session.get(DeploymentNotificationPolicy, recipient.deployment_id)
legal_basis = policy.legal_basis if policy else "consent"
if legal_basis == "consent":
# Query latest NotificationConsentEvent for (application_id, channel)
# Missing or granted=False → block with gate="consent"
8.4 Preflight check
run_preflight() warns authors if the procedure form lacks a consent_<channel> requirement (field_name LIKE 'consent_%'). This is a design-time warning, not a runtime block.
9. Kill Switch
9.1 Model
platform_notification_kill_switch is append-only. Every flip writes a new row. Latest enabled_at wins.
9.2 Queue-time check
latest_ks = select(NotificationKillSwitch)
.where(deployment_id=recipient.deployment_id, channel=channel)
.order_by(enabled_at.desc())
.limit(1)
if latest_ks and latest_ks.enabled:
return EligibilityResult(ok=False, gate="kill_switch", reason=latest_ks.reason)
9.3 Runbook behaviour
- Flip ON → all new events on that
(deployment, channel)are suppressed. - In-flight rows (
queued/attempting/failed_transient) have their next retry blocked; already-in-flight provider calls may still deliver. - Force-suppress in-flight → explicit
UPDATE notification_deliveries SET status='suppressed', suppression_reason='kill_switch'. - Flip OFF → insert new row with
enabled=FALSE.
10. Health Metrics
10.1 Architecture
- Writer:
refresh_notification_health_snap(deployment_id)— Task 10 periodic job - Reader:
NotificationHealthService— Task 9 thin read-side - Projection:
notifications_health_snapshots
10.2 Refresh cadence
- Procrastinate periodic:
* * * * * - Internal gating:
300 swhen all providers arehealthy60 swhen any provider isdegradedordown
- Lag sweeper: separate gauge
notifications_health_refresh_lag_secondsages fromMAX(refreshed_at)
10.3 Provider snapshot computation
SELECT COUNT(*) AS n,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS ok
FROM (
SELECT status
FROM notification_deliveries
WHERE channel = :c
AND is_test = FALSE
AND created_at > now() - interval '24 hours'
AND status IN ('delivered', 'failed_transient', 'failed_permanent')
ORDER BY created_at DESC
LIMIT :max_sample_size
) w
Success rate = ok / n.
| Condition | Status |
|---|---|
sample_size < 20 | insufficient_data |
success_rate >= 0.95 | healthy |
success_rate >= 0.70 | degraded |
| otherwise | down |
10.4 Procedure snapshot
Per procedure_version_id with deliveries in last 24h:
consent_granted,consent_withdrawn,consent_rate_baselinedeliveries_attempted_24h,deliveries_delivered_24h,deliveries_failed_24hfailure_classify_breakdown— JSONB aggregate ofclassified_error → count
10.5 Reader freshness guards
NotificationHealthService._compute_status:
- Staleness:
now - refreshed_at > interval * 2.0→unknown - Sample size:
sample_size < 20→insufficient_data - Raw status: otherwise return stored
provider_status
11. Rate Limiting
11.1 Postgres-backed limiter
notification_rate_limits — composite PK (deployment_id, channel, window_start).
- Windowing: floors UTC to nearest multiple of
window_seconds(default10) - Mechanism:
INSERT … ON CONFLICT DO UPDATE SET request_count = request_count + 1 RETURNING request_count - Cap:
max_per_window(default50) - Cleanup:
cleanup_stale_windows(max_age_seconds=3600)— hourly periodic drops old rows
11.2 Usage in dispatch loop
allowed = await rate_limit_acquire(session, provider.deployment_id, delivery.channel)
if not allowed:
delivery.status = "failed_transient"
delivery.classified_error = "rate_limited"
This is a soft limit — the row stays failed_transient and will be retried on the next sweep.
12. Key Metrics
| Metric | Type | Purpose |
|---|---|---|
notifications_health_refresh_lag_seconds | Gauge | Seconds since last refresh |
notifications_health_snapshot_refresh_duration_seconds | Histogram | Wall-clock duration of refresh pass |
notifications_inbox_thread_projection_repair_count | Counter | Repair SP invocations |
notifications_inbox_deadline_auto_read_refused | Counter | Mark-read refused (ack-required) |
notification_dispatch_attempted_total | Counter | Per leased inbox row |
notification_dispatch_outcome_total | Counter | Terminal outcome |
notification_rate_limit_rejections_total | Counter | Rate-limit gate blocks |
notification_dlq_depth | Gauge | failed_permanent backlog |
13. Design Invariants
| Invariant | Rationale |
|---|---|
| Inbox row before eligibility | Legal defensibility — every triggered send either goes out or is explicitly suppressed by name |
| Eligibility checked twice | State can change between write and send (kill switch, consent withdrawal, contact bounce) |
| Non-reentrant ledger before inbox | Crash safety — prevents orphan deliveries that re-fan on retry |
| Append-only kill switch | Full audit trail; no toggle mutation |
| Exactly one active provider per (deployment, channel) | No fallback ambiguity |
| Thread projection via triggers | Inbox stays consistent without app-level coordination |
| Frozen procedure name in inbox | Applicant sees the name at submission time even if renamed later |
requires_acknowledgement on template | Legal-deadline fidelity requires explicit acknowledgement, not dwell-read |
| Zitadel sub as String(255) | Zitadel subs are numeric snowflakes, not UUIDs |
14. Further Reading
docs/specs/2026-04-20-smartlink-phase2d-notifications-design.md— Phase 2D design specdocs/specs/2026-04-21-smartlink-phase2e-inbox-health-design.md— Phase 2E design specsrc/opengov/platform/notifications/dispatch.py— Trigger resolution + queue-time logicsrc/opengov/platform/notifications/dispatchable.py— Execute-time logicsrc/opengov/eapproval/notification_threads/inbox_service.py— Inbox APIsrc/opengov/platform/notifications_health/refresh.py— Health refresh jobsrc/opengov/platform/notifications_health/service.py— Health read-side