Concepts
Notification lifecycle
The five statuses, what moves a record between them, scheduling and draining, failure, cancelling, updating, resending, requeueing and repinning.
Every notification is a record with a status. The service moves it forward; nothing else does. This page follows one record from creation to its terminal state and names the method behind each transition.
The five statuses
| Status | Meaning | Reached by |
|---|---|---|
PENDING_SEND | Created and not yet delivered. Scheduled notifications sit here until due | create_notificationcreateNotification |
SENT | An adapter delivered it. The sent_at / sentAt timestamp is set | A successful sendsend |
FAILED | An adapter raised during delivery | A failed sendsend |
READ | An in-app notification the user has opened. read_at / readAt is set | mark_readmarkRead |
CANCELLED | Withdrawn before it was sent | cancel_notificationcancelNotification |
The transitions are strict. Only a PENDING_SEND record can become SENT, FAILED or CANCELLED; only a SENT record can become READ. A FAILED or CANCELLED record can go back to PENDING_SEND by requeueing it, which retries the same record. SENT and READ are terminal: to send a delivered notification again, resend it as a new record.
Create, then send
create_notificationcreateNotification always writes the record first and returns it. Whether it also sends depends on send_aftersendAfter:
- Unset, or a time in the past: the service calls
sendsendon the new record before returning. - A time in the future: the record stays
PENDING_SENDand the call returns at once.
import datetime
notification = service.create_notification(
user_id=user.id,
notification_type=NotificationTypes.EMAIL,
title="Trial ending",
body_template="billing/trial_ending.html",
subject_template="billing/trial_ending_subject.txt",
context_name="trial_ending",
context_kwargs={"user_id": user.id},
send_after=datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(days=7),
)
notification.status # "PENDING_SEND"send_after is compared against datetime.now(tz=utc), so pass an aware datetime.
const notification = await vintasend.createNotification({
userId: user.id,
notificationType: 'EMAIL',
title: 'Trial ending',
bodyTemplate: './templates/billing/trial-ending.html',
subjectTemplate: './templates/billing/trial-ending-subject.txt',
contextName: 'trialEnding',
contextParameters: { userId: user.id },
sendAfter: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
extraParams: null,
});
notification.status; // 'PENDING_SEND'sendAfter is required in the input; pass null to send immediately.
Draining scheduled notifications
Nothing in the library runs on a timer. A scheduled record waits until something calls send_pending_notificationssendPendingNotifications, which asks the backend for every PENDING_SEND record whose send_aftersendAfter is unset or in the past and sends each one. Call it from whatever already runs periodic jobs for your application; once a minute is a common choice.
send_pending_notifications() never raises. Each failure is logged against its notification id, and a summary of sent and failed counts is logged at the end. The sync service sends sequentially; AsyncIONotificationService sends with asyncio.gather.
vintasend.tasks.periodic_tasks.periodic_send_pending_notifications is a ready-made entry point for workers. Without an argument it builds the service from the NOTIFICATION_SERVICE_FACTORY setting (resolved once per process and cached); with an explicit service it uses that.
# Celery Beat
from celery import Celery
from vintasend.tasks.periodic_tasks import periodic_send_pending_notifications
celery_app = Celery()
send_pending = celery_app.task(periodic_send_pending_notifications)
celery_app.conf.beat_schedule = {
"vintasend-send-pending": {"task": send_pending.name, "schedule": 60.0},
}# A management command, a cron entry, or any script
service = build_notification_service()
service.send_pending_notifications()sendPendingNotifications() sends every due record with Promise.all. An adapter failure marks that record FAILED and does not stop the others. With raiseErrorOnFailedSend: true, a record with no adapter for its type or a failing context generator rejects the whole call.
There is no bundled scheduler. Call the method from a cron job, a worker loop, or a scheduled task runner:
import cron from 'node-cron';
cron.schedule('* * * * *', async () => {
await vintasend.sendPendingNotifications();
});The process that runs this needs the same contextGeneratorsMap and adapters as the one that created the notifications, since context is generated here.
What happens on failure
Inside sendsend, an adapter that throws moves the record to FAILED. The record keeps its template, context name and arguments, so it can be inspected and resent later.
Error handling is governed by the raise_on_failed_send constructor flag.
False(the default): every failure is logged and the remaining adapters still run.create_notificationreturns normally; the stored record isFAILED, so re-read it rather than trusting the returned object’s status.True: the failure is raised to the caller asNotificationSendError(adapter failed),NotificationContextGenerationError(generator failed; the record is also markedFAILED),NotificationQueueServiceMissingError(background adapter with no queue service),NotificationMarkFailedErrororNotificationMarkSentError(the backend could not record the outcome).
Marking FAILED happens before raising, so the record reflects what happened either way. delayed_send, the worker half of background sending, follows the same rules, with one addition: NotificationNotFoundError propagates regardless of the flag, because an id that resolves to nothing is a wiring problem rather than a failed send. A worker that receives the same id twice skips a record that is already SENT, READ or CANCELLED.
Error handling is governed by the raiseErrorOnFailedSend option passed to the factory, false by default.
- An adapter error is logged, the record is marked
FAILED, andsendmoves on to the next adapter. This never throws, whatever the option:FAILEDon the record is the signal. - A missing adapter for the notification’s type and a failing context generator are logged and leave the record untouched with the option
false; withtruethey throw. A background adapter with no queue service is logged and skipped either way.
delayedSend, the worker half of background sending, marks FAILED when the adapter throws, and with the option true throws for a missing record or a missing background adapter.
Cancelling
cancel_notificationcancelNotification withdraws a PENDING_SEND record. It takes only the notification id and returns nothing.
service.cancel_notification(notification.id)Raises NotificationCancelError when the record is not pending: already sent, already cancelled, or missing. The Django and SQLAlchemy backends and the in-repo fake keep the row with status CANCELLED, and get_notification returns it, so a cancelled notification can be requeued. A backend that deletes cancelled rows instead can only requeue failed ones. Cancelling never deletes attachment files.
await vintasend.cancelNotification(notification.id);The service delegates to the backend’s cancelNotification and logs the outcome. Whether a non-pending record throws, and whether the row is marked CANCELLED or removed, is the backend’s decision; check the backend package you use.
Updating before it is sent
A pending record can be edited. Both libraries refuse to change the fields that identify the record or that the service manages itself.
service.update_notification(
notification.id,
send_after=new_date,
body_template="billing/trial_ending_v2.html",
)update_notification(notification_id, pin_template_versions=None, **kwargs) accepts title, body_template, context_name, context_kwargs, send_after, subject_template, preheader_template, adapter_extra_parameters, attachments and requested_template_version. After the write, if the record is PENDING_SEND and its send_after is now unset or in the past, the service sends it immediately, exactly as create_notification would. A FAILED or CANCELLED record can be updated too, and stays where it is until it is requeued.
Three fields raise rather than change: tenant (TenantReassignmentError), git_commit_sha (GitCommitShaReassignmentError) and used_template_version (UsedTemplateVersionReassignmentError). The last two are written only by the service at send time. user_id, notification_type and status are not in the accepted keyword set at all.
await vintasend.updateNotification(notification.id, {
sendAfter: newDate,
bodyTemplate: './templates/billing/trial-ending-v2.html',
});updateNotification(notificationId, fields, options?) takes a Partial of the notification minus id and tenant. Passing tenant or usedTemplateVersion throws; gitCommitSha is typed as never. The service persists the update and returns the record. It does not send: moving sendAfter into the past makes the record due, and the next sendPendingNotifications picks it up.
Resending
resend_notificationresendNotification is the operation behind a dashboard’s “retry” button. It does not touch the source record. It clones the source into a new PENDING_SEND record with send_aftersendAfter unset, sends the clone, and returns it. The source keeps its id, status and timestamps, so a FAILED record stays FAILED and the history stays honest.
Two kinds of record are refused: one-off notifications (they have no user record to clone from; recreate them instead) and notifications still scheduled in the future (cancel or update those instead).
clone = service.resend_notification(notification.id)
clone = service.resend_notification(notification.id, use_stored_context_if_available=True)The refusals raise NotificationResendError. The clone copies the user, type, title, templates, context name and arguments, adapter parameters, tenant and attachments. With use_stored_context_if_available=True and a stored context_used on the source, the clone is sent with that context verbatim; otherwise context is generated again. Send failures follow raise_on_failed_send as above.
const clone = await vintasend.resendNotification(notification.id);
const same = await vintasend.resendNotification(notification.id, true);A refusal (not found, one-off, scheduled in the future, or useStoredContextIfAvailable with no stored context) is logged and the method returns undefined; with raiseErrorOnFailedSend: true it throws. The clone copies the user, type, title, templates, context name and parameters, extraParams and tenant. Its contextUsed is set at creation, from the source’s stored context or from a fresh generation, and the send is started without being awaited, so the returned clone is still PENDING_SEND at the moment it is returned.
Requeueing
requeue_notificationrequeueNotification puts a FAILED or CANCELLED record back into PENDING_SEND, so it is sent again. Unlike resending, it keeps the record: the id, content, template pin, stored context, adapter used, git commit SHA and attachments all stay as they are. It clears sent_atsentAt.
send_aftersendAfter decides when the retry goes out. Left out, the record keeps its own. None / null means “now”. Once the record is pending again, it is due when that value is unset or in the past, and then it is sent at once, the same as on create. An adapter that uses the queue service puts it back on the queue. A future value leaves it for whatever sends pending notifications, and so does send set to false, even for a due record. No adapter is used then, so a process that only requeues can be built with no adapters and no delivery credentials.
It returns the record as it stands after any send it started, read again from the primary backend: SENT when it went out, FAILED when the adapter failed, PENDING_SEND when it is waiting. That holds when the service is configured not to raise on a failed send, so read status to know what happened.
template_versiontemplateVersion pins that version in the same backend write that requeues, so the record is never left pinned but not pending, or pending on the old pin. Repinning first and requeueing after still works, in two writes.
PENDING_SEND is refused because it is already queued. SENT and READ are refused because requeueing a delivered notification would deliver it twice under one record; resend it instead.
service.requeue_notification(notification.id) # keep its send_after
service.requeue_notification(notification.id, send_after=None) # send it now
service.requeue_notification(notification.id, send_after=tomorrow)
service.requeue_notification(notification.id, template_version=4) # pin it in the same write
service.requeue_notification(notification.id, send=False) # leave it for the pending senderA refusal raises NotificationActionError before anything is written. Branch on its reason: NOT_FOUND, INVALID_STATUS, CHANGED or UNSUPPORTED (see moving notifications safely). It also carries action ("requeue"), notification_id and, for a status refusal, status. The message names the notification by id only, so it is safe to log. A stored context_used is reused for the send rather than generated again. The write goes to the primary backend and then to every additional backend, like every other write.
REQUEUEABLE_NOTIFICATION_STATUSES in vintasend.constants lists the allowed statuses. Every backend implements requeue_notification, which checks the status and writes in one step, so two callers racing cannot both succeed.
await vintasend.requeueNotification(notification.id); // keep its sendAfter
await vintasend.requeueNotification(notification.id, { sendAfter: null }); // send it now
await vintasend.requeueNotification(notification.id, { sendAfter: tomorrow });
await vintasend.requeueNotification(notification.id, { templateVersion: 4 }); // pin it in the same write
await vintasend.requeueNotification(notification.id, { send: false }); // leave it for the pending senderA refusal throws NotificationActionError before anything is written, with reason set to NOT_FOUND, INVALID_STATUS, CHANGED or UNSUPPORTED. Test for it with isNotificationActionError, which also recognises the error from another copy of the package. REQUEUEABLE_NOTIFICATION_STATUSES lists the allowed statuses, and every backend implements requeueNotification.
Repinning to a template version
repin_notificationrepinNotification changes which template version a record renders. Use it after publishing a fixed template, to move notifications that were not delivered onto the fix. An update keeps the pin unless the body template changes, so updating cannot do this.
It works on PENDING_SEND, FAILED and CANCELLED records, whether they were pinned before or not. SENT and READ are refused, because a delivered record’s pin records what it was asked to render. Without a version, the record is pinned to get_current_template_versiongetCurrentTemplateVersion: what the template renderer for its type reports as current, the same answer pinning on create records. It changes nothing else: it neither sends nor changes the status. Repinning to the version already pinned writes nothing.
A backend that implements its own repin checks the status in the same write, so a worker sending the record in between is never overwritten. Otherwise the service writes through the generic update.
service.repin_notification(notification.id) # the current version
service.repin_notification(notification.id, template_version=4) # a version you name
service.get_current_template_version("EMAIL", "welcome") # what the first line pinsA template_version that is not a non-negative int raises InvalidTemplateVersionError, a ValueError, before anything is read. A bool is refused too. Other refusals raise NotificationActionError with reason set to NOT_FOUND, INVALID_STATUS, NO_TEMPLATE_VERSION when no version was given and the renderer reports none, CHANGED or UNSUPPORTED. A renderer that raises is logged and counts as reporting none. REPINNABLE_NOTIFICATION_STATUSES lists the allowed statuses.
await vintasend.repinNotification(notification.id); // the current version
await vintasend.repinNotification(notification.id, { templateVersion: 4 }); // a version you name
await vintasend.getCurrentTemplateVersion('EMAIL', 'welcome'); // what the first line pinsAn invalid templateVersion throws a RangeError. Other refusals throw NotificationActionError with reason set to NOT_FOUND, INVALID_STATUS, NO_TEMPLATE_VERSION, CHANGED or UNSUPPORTED. REPINNABLE_NOTIFICATION_STATUSES lists the allowed statuses.
Moving notifications safely
To move many records onto a fixed template, list them without reading them, then act on each only if nothing has changed since it was listed.
filter_notification_versionsfilterNotificationVersions takes the composable filter and returns the id and an opaque version token of each match, ordered by id, and nothing else: the backend reads no recipient, context, context parameters, rendered content or attachment to answer it. The token changes on every write to the record, by anyone; compare tokens for equality only. Pass it back as expected_versionexpectedVersion to a repin or a requeue, and the move happens only if the record is still at that version. Otherwise the action is refused with CHANGED and nothing is written. Moving what you list changes what matches, so list again from the first page rather than moving on to the next one.
stranded = {"and": [{"body_template": "welcome"}, {"status": NotificationStatus.FAILED}]}
while page := service.filter_notification_versions(stranded, page=1, page_size=100):
for entry in page:
try:
service.requeue_notification(
entry.id, template_version=4, expected_version=entry.version
)
except NotificationActionError as error:
if error.reason != "CHANGED":
raise
# written since it was listed; the next listing carries its new versionconst stranded = { and: [{ bodyTemplate: 'welcome' }, { status: 'FAILED' }] } as const;
let page = await vintasend.filterNotificationVersions(stranded, 0, 100);
while (page.length > 0) {
for (const { id, version } of page) {
await vintasend.requeueNotification(id, { templateVersion: 4, expectedVersion: version });
}
page = await vintasend.filterNotificationVersions(stranded, 0, 100);
}These are optional backend features. get_backend_supported_action_capabilitiesgetBackendSupportedActionCapabilities reports which ones the primary backend supports, every key false by default:
| Key | True when |
|---|---|
repin.expectedVersion | the backend’s repin checks the expected version |
requeue.expectedVersion | the backend’s requeue checks the expected version |
requeue.templateVersion | the backend’s requeue pins in the same write |
versions.filter | the backend lists versions |
An option the primary backend does not report is refused with UNSUPPORTED before anything is read or written, never passed to a backend that would ignore it. Additional backends take every write unconditionally, because a version token belongs to the primary; one that cannot pin in the same write as a requeue is repinned and then requeued. The fakes, vintasend-django, vintasend-sqlalchemy, vintasend-prisma and vintasend-medplum support all four.
Every Notification and OneOffNotification carries its current token in notification_version (None from a backend that keeps no token), so a notification you already hold can be moved without listing:
notification = service.get_notification(notification_id)
service.repin_notification(notification.id, 4, expected_version=notification.notification_version)Tokens also replicate: the primary issues them and replication carries them to additional backends, so filter_notification_versions(..., backend_identifier="replica") lists versions the primary accepts. A replica that lags behind gives a token the primary refuses, usually with CHANGED (a requeue checks the status first, so a notification that has moved on can be refused with INVALID_STATUS); list again. A fifth key, writes.notificationVersion, lets a replica that replays writes take the primary’s token on each one; see version tokens on replicas.
vintasend-ts does not carry version tokens across replicas yet.
Found a mistake? Edit this page on GitHub.