Context
Instructors, students and admins need to hear about more events (grading, receipts, AI provider outages…). Only one of them, a new submission, also went by email, sent inline from the request. Resend's free tier allows 100 emails a day, so email has to be rationed. The team also wants fewer emails, not more.
Decision
- Every event gets an in-app notice. An event gets an email only when the recipient must act and is probably not on the platform, when it involves their money or points, or when it is about security or the system going down. Social events (likes, comments, badges) are in-app only. The bell keeps its 15 s poll and also refetches on window focus. There is no SSE: a 15-second delay does not matter for coursework.
- One path: the
notifyBullMQ queue. A producer emits an event (NotifyJobData, a Zod union inshared): a type plus ids, never rendered text or addresses. The api consumes the queue (NotifyQueueService→NotifyDispatcherService), as it doescourse-refund(ADR-0046), because the mail transport, the templates, the notices and the preferences all live there. The worker produces events too; it does not send mail. Without Redis the event is dispatched in-process.emitnever throws. - The dispatcher handles each event the same way. A handler per event type reads current rows and names recipients. Then, for each recipient: 1. the notice is written once per (recipient, kind, entity) (
createOnce); 2. the email goes only to an active account, only if the recipient has not switched that category off, and only outside the category's cooldown (acquireCooldown); 3. a failed email is rethrown so the job retries. A Redis marker per (event, recipient) stops the retry from resending emails that already went. - Email categories (
email-categories.ts): - Optional ones arenormalpriority and have a per-user toggle (User.notifySubmissionEmail,notifyGradingReminderEmail,notifyGradedEmail, all default on, set from the profile page): submissions, grading reminders, graded. - Mandatory ones arecritical: payment and refund, course status, admin system alerts. Password reset stays a directcriticalsend. - Daily quota in
MailService. Every send counts against a Redis counter per Asia/Ho_Chi_Minh day. Anormalemail beyondMAIL_DAILY_NORMAL_LIMIT(default 80) is skipped and comes backskipped-quota; its notice still lands in the bell. Acriticalemail always goes. The first skip of the day gives every admin oneEMAIL_QUOTA_REACHEDnotice. A broken counter fails open.
Consequences
- A slow or failing SMTP server never touches a request, and a failed email is retried instead of lost.
- On a heavy day the 20 emails left after the cap are kept for what matters most.
- New events cost one union variant and one handler; the policy around them is already built.
- The quota counter is approximate: a send that then fails at SMTP still counts. Being conservative is the right side to err on for a hard provider cap.
Addendum (#217, instructor events)
- Hourly batch. The first submission on an assignment in an hour is emailed at once. A later one in that hour only gets its notice, and the dispatcher returns a follow-up:
submission.digest, delayed one hour, with a job id per (owner, assignment) so it is scheduled only once. When that hour is up, one email counts everything submitted since the owner's last email. A failed send releases the hour's window, so the retry is not mistaken for a second email. Without Redis there is no batch. - Morning reminder. A BullMQ job scheduler on
notify(grading-reminder, 08:00 Asia/Ho_Chi_Minh), upserted at api boot, emitsgrading.reminder. It covers each student's latest version that is stillreviewState = 'PENDING'more than 3 days after submission. - Enrolments are in-app only, folded per course per day. A take-down is always emailed.
Addendum (#218, student events)
- The worker produces events too.
apps/worker/src/notify.tsis anotifyqueue producer indeps.notify. The grading worker emitssubmission.testedonce a submission's tests have run. The api still delivers everything. - Emails.
submission.graded(when the instructor finalises a grade) sends the optional "graded" email.purchase.settled(PAID or FAILED; not CANCELLED or EXPIRED) andpoints.refundedalways email: they are about money. A refund's bell line is still written inside the refund transaction, so its event carries only the email. - In-app only. A new assessment (folded per course per day), a deadline in about 24 hours (hourly scheduler, students who have not submitted), and the 20:00 streak reminder (students active yesterday but not yet today, by Vietnam date).
NotificationsModuleimportsMailModuleitself, so a module that pulls it in transitively (Points → Notifications) builds in tests without wiring mail.
Addendum (#219, admin alerts)
- Key pool.
createAiClienttakesonPoolEventand hands it to the Gemini key pool. The api and the worker passcreatePoolAlertForwarder(shared), which turnskey_revoked,all_keys_unavailableandkey_recoveredintoai.key-poolevents. Each process sends at most one per status (and per key) every 5 minutes. A 429 cooldown is routine and is not an alert. Only the pool's own id (key_1) leaves the process, never a key. - All keys down: notice, plus an email at most once per admin per 6 hours. It also sets a flag, so "Gemini đã hoạt động lại" is said once, and only after an outage. - One key refused: in-app only, once per key per day. - Budget.
AiBudgetWatchServicereads the shared counter every 10 minutes. At 80% admins get an in-app notice; at 100%, a notice and an email. Each level is sent once per day. - Payments. A callback with the wrong amount, or a PAID callback after expiry (no points granted, an admin must ADJUST), gives admins a notice and an email per purchase.
- Moderation. A new report or a post submitted for review gives each admin one notice, folded per day, counting the open reports and the posts waiting for review.
- Not built: organisations waiting for verification. The api has no verification flow yet.