Skip to Content
DocsFeaturesMessageOverview

Message

message-starter sends three kinds of message for an application: email, SMS and inbox notifications. Business code calls MessageService: for an email or an SMS it writes one send record and returns, and the delivery loop sends the message in the background, retrying or stopping by the cause when it fails; an inbox notification is written straight into its recipients’ inboxes. Whether an email or an SMS went out, and why not, is all recorded on its send record.

Overview

Email and SMS take the same path: acceptance only writes a record, and delivery happens in the background. No message queue sits between the two — the send record itself is the queue.

The parts

  • Caller: business modules, and framework modules such as user-starter and Flow’s notifications. It calls MessageService and, once it has the record id, carries on with its own work.
  • Acceptance (MessageService): checks only what the caller got wrong — the recipients, the address or number format, whether there is content or a template — and writes one Pending record per message.
  • Send record (MailSendRecord, SmsSendRecord): everything that happens to one message — the request as it was made, the preparation result, the attempt count, the error code and reason, the send time. Neither table is split by tenant: tenantId on a record only says whom it is filed under, see Tenant tier and platform tier.
  • Delivery loop (DeliveryPoller): a pool of workers per instance and per channel, claiming due records and handing them to the processor.
  • Processor: one for mail, one for SMS. On the first attempt it prepares the record (renders the template, chooses the server or provider, charges the day’s and the month’s quota); then it rate-limits, sends and records the outcome.
  • External services: SMTP servers and SMS providers. A message counts as sent once they accept it; whether it then arrives shows in bounces or the provider’s receipts.
  • Stuck-send sweep (ZombieRecordSweeper): every minute, puts records stuck in Sending for over 5 minutes back to retry.

The main path

Caller's transactionrolls back: no recordShort transactionsclaim, write-back, outcome⑪ no transactionholds no connectionBackgroundCallerMessageServiceSend recordDelivery workerProcessorSMTP / providersend mail or SMSsendMail / sendSmscheck the caller's inputrejected: throws, writes nothingwrite a Pending recordrequest, trace idreturn the idcommits with callerread due recordsPending, or due Retryclaim: set Sendingif lost, try the nexthand overprepare the recordrender, route, charge quotawrite the preparation backretries replay it as israte limitdaily and per-minute capssendrecord the outcomeSent, or Retry, Failed, DeadLetterclaim the next one at onceidle only when nothing is due12345678910111213First attempt only

①–④ run in the caller’s transaction: if the caller rolls back, the record does not exist either. When acceptance rejects a request, it throws at once and writes nothing, without marking the caller’s transaction rollback-only. Every step after that runs in the background and has nothing to do with the caller.

⑥ the claim, ⑨ the write-back and ⑫ the outcome are one short transaction each; ⑪ the send runs in no transaction and holds no database connection while it sends. ⑧ and ⑨ happen on the first attempt only: a retry replays the prepared content, server and provider as they are. When ⑪ has gone out but ⑫ was not written, the record stays Sending, is put back to retry after 5 minutes and is sent again: delivery is “at least once”.

Who implements each step

① ② ③: MessageServiceImpl hands the request to MailMessageHandler / SmsMessageHandler, which check it, build the record and write its tenantId from the calling tenant context (the send record tables are not multi-tenant, so the ORM stamps nothing on them). ⑤ ⑥ ⑦ ⑬: DeliveryPoller. ⑧–⑫: MailDeliveryProcessor / SmsDeliveryProcessor; ⑩ is RateLimiter, and a failure at ⑫ goes to SendFailureHandler, which decides on retry, failure or dead letter. Every status change goes through the framework’s versionLock (AbstractCasSendRecordServiceImpl). Which transaction each step falls in: see Design notes.

Send record statuses

Mail and SMS send records share one set of statuses. Only the delivery loop, the processors, the stuck-send sweep, bounce handling when mail is received, and an operator’s Retry change a status; the caller never does.

WaitingSending, or retryingSettledacceptedclaimedserver acceptednot retryable5th retry failedretryable failureor stuck 5 minclaimed when duebounce(mail)manual RetryPendingPendingSendingSendingRetryRetrySentSentFailedFailedDead letterDeadLetter

Failures come in two kinds: Failed is one that retrying will not fix, such as a configuration, template or quota problem found during preparation; DeadLetter one that still fails after 5 retries. Both need a person: fix the cause, then press Retry on the record. Which errors count as which: see Failures and retries. When a bounce comes back for a sent mail, Sent becomes Failed.

StatusMeaningNext
PendingAccepted, waiting for deliveryClaimed at the next poll, or as soon as a worker is free
SendingA worker is preparing or sending itLeaves once the outcome is recorded; stuck for over 5 minutes, it goes back to Retry
SentThe server or provider accepted itFinal; a mail that bounces becomes Failed
RetryA temporary failure, waiting until next_retry_atClaimed again once that time comes
FailedA failure that retrying will not fixRetry by hand after fixing the cause
DeadLetterAll 5 retries failedRetry by hand once the cause is found; it is also archived into the dead-letter table

Three channels

ChannelSent toRecordThrough the delivery loopSee
EmailEmail addresses, possibly severalMailSendRecordYesEmail
SMSOne E.164 numberSmsSendRecordYesSMS
Inbox notificationSystem usersInboxNotificationNo, written directlyInbox

One email may have several recipients, CCs and BCCs, all sharing one record; an inbox notification is written into the inbox during the call and has no send status.

Sending from business code

Inject MessageService and call it. It only accepts the message: the id it returns points at a Pending record and does not mean the message has gone out; the record tells how the send went.

ChannelSingleBatch
EmailsendMail(SendMailDTO)sendMailBatch(List<SendMailDTO>)
SMSsendSms(SendSmsDTO)sendSmsBatch(List<SendSmsDTO>)
Inbox notificationsendInbox(SendInboxDTO)sendInboxBatch(List<SendInboxDTO>)
@Autowired private MessageService messageService; // A template of the sender's own tier, rendered with this recipient's variables. Long mailId = messageService.sendMail(SendMailDTO.ofTemplate( List.of("[email protected]"), "USER_WELCOME", Map.of("name", "Alice"), MessageScope.TENANT)); Long smsId = messageService.sendSms(SendSmsDTO.ofTemplate( "+8613800138000", "VERIFY_CODE", Map.of("code", "123456"), MessageScope.TENANT)); // Both ids point at Pending records; the delivery loop moves them on.
  • One DTO, one message. An email may have several recipients and still has one record; an SMS goes to one number only. Batch methods take 1 to 500 items, check them all before writing any, and return the ids in input order.
  • Acceptance checks only the caller’s mistakes. With no recipient, a malformed address or number, or neither content nor a template, it throws BusinessException and writes nothing; for email and SMS, this rejection does not mark the caller’s transaction rollback-only. A caller that must not fail because one notice cannot be sent catches it and logs it at ERROR, as user-starter’s notices do. A value longer than its field (subject 500 characters, Reply-To 255, number 50, SMS content 2000) is reported only when the record is written: the caller’s transaction is then marked rollback-only, and in a batch the items before it have already been written.
  • Configuration problems are not reported at acceptance. No server or provider, a missing template, a used-up daily or monthly quota: each turns the record Failed on its first attempt, with a marker code and an ERROR log — see First attempt: preparing the record. By then the caller has long had the record id.
  • The record commits with the caller’s transaction. If the caller rolls back, the record is gone too and nothing is sent.
  • Sending for another tenant. A send is filed under the tenant the call is made in, TENANT and PLATFORM alike, and counted against its quota. A scheduled job, an anonymous link that carries its tenant, or a platform notice about one of a tenant’s accounts sends for that tenant by making the call inside ContextUtils.inTenantContext(tenantId, …). A send made with no tenant context is filed under the platform (tenantId = -1).
The dependency, who calls it, and why there is no synchronous send
<dependency> <groupId>io.softa</groupId> <artifactId>message-starter</artifactId> <version>${softa.version}</version> </dependency>

Every module that sends mail or SMS depends on message-starter directly and calls MessageService, with no request event in between — user-starter’s login codes, invitations, account notices and subscription reminders included.

There is no synchronous variant: an SMTP 250 OK does not mean the user has received the message, and with a single asynchronous path, no request thread is held up by an external service. The send record tables are not multi-tenant, so the ORM stamps no tenant on them: acceptance writes tenantId itself — the current context’s tenant, -1 when it has none, whatever the scope — so a record written by a cross-tenant caller is still filed under someone. The mail and SMS acceptance methods declare noRollbackFor = BusinessException; the inbox ones do not, so their rejection leaves the caller’s transaction rollback-only.

Tenant tier and platform tier

With multi-tenancy on, the platform’s and the tenants’ messaging data are stored apart, by two rules only: data that belongs to one side only is split into tables by owner; data the platform handles for everyone sits in one table not split by tenant, the tenant id recording only whom a row is filed under. A send states whose message it is with its send scope, MessageScope.

DataThe platform’s: not multi-tenant, only under platform navigationA tenant’s: multi-tenant, each tenant sees only its own
Send serverPlatformMailSendServerMailSendServerConfig
Receive serverPlatformMailReceiveServerMailReceiveServerConfig
Received mailPlatformMailReceiveRecordMailReceiveRecord
IMAP watermarkPlatformMailFetchWatermarkMailFetchImapWatermark
Mail templatePlatformMailTemplateMailTemplate
SMS providers, country routes, SMS templates, template bindingsSmsProviderConfig, SmsProviderRegion, SmsTemplate, SmsTemplateProviderBinding: no tenant column, as SMS is a platform service—
Inbox notification—InboxNotification
  • Data that belongs to one side only is split by owner. For each row above, the platform’s data and the tenants’ are in tables of their own, and a read of one table never falls back to the other. The platform’s configuration is no longer tenant_id = -1 rows of the tenants’ tables.
  • Data the platform handles for everyone is not split by tenant. The send records (MailSendRecord, SmsSendRecord, which are the delivery queue), dead letters, quotas and usage are each one table not split by tenant, with the tenant id (tenantId; sourceTenantId on dead letters) as an attribution column only. The platform’s pages read the whole table; a tenant reads its own mail send log through TenantMailSendRecord, a read-only projection over the mail send record table, isolated by tenant, with no bodies, template variables or attachments. The SMS send log has no tenant view.
Send scopeUsed forMail templateSend server / SMS provider
TENANT (default)The tenant’s business messagesThe current tenant’s MailTemplateMail: the tenant’s enabled default send server, or, when it has none, relayed through the platform’s default send server; SMS: routed by country
PLATFORMPlatform messages such as account credentials, security notices and billingPlatformMailTemplateMail: the platform’s send servers only; SMS: routed by country
  • Whom a record is filed under, and whose quota it draws on, does not depend on the scope. A message made for a tenant is filed under that tenant and counted against its quotas (the daily cap and the monthly allowance), and is refused once they are spent; so is a platform message, such as a security notice about one of the tenant’s accounts, the sign-in code or password reset of someone with an account in that one company, or a subscription reminder. Which tenant a send is made for is the tenant context of the call. Only a send no tenant can be named for is filed under the platform (-1) and draws on the platform’s own quota: the sign-in codes and password resets of someone with accounts in several companies, or the messages of the platform’s own staff.

  • One template code lives in one tier. A tenant template may not take a code a platform template already has, and every write path refuses it: the template pages, import, seed loading. When the send scope and the template’s tier do not match, the record fails with TEMPLATE_NOT_RESOLVABLE and a message naming the scope to use. SMS templates exist once, on the platform: for SMS the scope has no effect and is only recorded on the send.

  • The platform tenant has tenant-tier templates of its own. A TENANT-scope mail the platform tenant (-1) sends — the invitation of a new platform staff account, say — reads the platform tenant’s own MailTemplate rows, like any tenant’s, and never the platform templates. The platform tenant runs no tenant seed files, so these rows go in the application’s data-platform seed files.

  • Sending crosses one way only. A tenant’s mail may be relayed through the platform; the platform’s mail goes out through the platform’s servers only and never through SMTP a tenant configured. The record keeps the send server’s owner, serverOwner (Tenant / Platform), with the server’s id, and retries replay them as they are.

  • Receiving never crosses. Received mail belongs to the owner of the receive server it arrived through. Bounces and read receipts can be matched only to records the same owner’s send servers carried: the platform’s receive servers match the platform’s own mail and the tenants’ mail it relayed, a tenant’s receive servers only that tenant’s mail sent through its own servers; see Email.

  • Quotas count only the platform’s infrastructure. Every SMS is charged; mail is charged when a platform send server carries it, relayed tenant mail included; a tenant’s mail through its own server is not; see Send quotas.

  • Security notices are the platform’s. Every password reset, and the three security notices user.reset-user, user.enterprise-email-changed and user.login-mobile-changed, are sent with PLATFORM: from platform templates and through the platform’s servers only, so a tenant can neither reword nor swallow them.

  • The platform’s pages go under platform navigation. The platform’s tables are not split by tenant: put under navigation a tenant can reach, they show it every row. The permission layer is what keeps tenants out: navigations under the platform prefixes (permission.platform-nav-prefixes) are left out of tenant admins’ and consultants’ menus, and permission-starter drops them, and the permissions that hang off them, from a tenant’s own roles. An application may also list these models’ paths in permission.platform-only-patterns, which bars tenant admins and consultants at the path.

  • The send records have a second line. The list and detail endpoints of /MailSendRecord and /SmsSendRecord (searchPage, searchList, getById) and their retries also refuse a tenant caller in code; the two tables’ other generic model routes are left to the permission layer. A tenant reads and retries its own mail records on its send log page (/TenantMailSendRecord). /api/mail/status and /api/sms/status answer a tenant only for its own records.

  • A tenant’s servers must be on the internet. A tenant’s own send or receive server whose host is, or resolves to, an address inside the deployment is refused on save and before every connection; see Email.

  • Background jobs run in the owner’s context. Delivery, the scheduled mail fetch and the stuck-send sweep all scan across tenants. Delivery and the sweep run in the tenant the record is filed under, delivery also under the trace id of the request that submitted the record; the scheduled fetch runs in the server owner’s context: a platform server in the platform’s, a tenant’s in that tenant’s.

  • With multi-tenancy off there is one owner. Nothing is filtered or stamped, and the send scope stops mattering: every send takes the deployment’s own default send server and template first (MailSendServerConfig, MailTemplate), then the platform table’s; a send server named by id is used from whichever of the two tables holds it.

How template seeds reach each tier

Tenant templates are seeded by the tenant files in the application’s seed-manifest.yml, which seed-starter runs when a tenant is provisioned. A tenant runs each seed file only once, so a new template reaches existing tenants as a new tenant file, run by the platform administrator. When the application gives its template file mode: append, a new template is simply added to that file: on the platform administrator’s next run it is created only in tenants that lack it; where a tenant already has a template of that code but no seed binding (inserted by a script or created by hand), the binding is added by code and the template is kept as it is, never created a second time. A change to a template existing tenants already have always goes out as a data migration, with the seed file changed too, for tenants provisioned later.

Platform templates (PlatformMailTemplate) are in the application’s platform seed file and are written by the platform load. A platform file that changed rewrites all its rows when it is loaded again, so a platform template the platform administrator edited on its page is overwritten. A code goes in one seed only: a tenant seed holding a platform template’s code is refused when it loads.

Configuration and dependencies

message-starter depends on the database and Redis: if either is unavailable, the operations that need it fail outright, with no degraded mode. Sending does not depend on Pulsar, which is used only for the scheduled mail fetch and for archiving other consumers’ poison messages.

DependencyUsed byWhen it is unavailableOperational requirement
DatabaseEverything: send records, status changes, quota countersOperations fail; the caller gets a 5xxA highly available database
RedisRate-limit counters, the cache of server and provider configurationOperations fail; the caller gets a 5xxSentinel or Cluster; the K8s readiness probe includes /actuator/health/redis, so the load balancer routes traffic away while Redis is unreachable
PulsarScheduled mail fetch (CronTaskMailFetchConsumer), poison-message archiving (DeadLetterConsumer)Fetching and archiving pause, and carry on once it is back; sending is unaffectedSending does not depend on it
SMTP servers, SMS providersOutbound sendingEach record retries or fails by its error categorySet the local rate limits below the provider’s quota

There is deliberately no in-process fallback when Redis is down: local rate limiters would have each instance count on its own, and a long enough outage could blow through a provider’s daily quota and cost real money. Refusing traffic at the load balancer through the readiness probe is safer than silently multiplying the send volume during a partial failure.

Properties

Prefix softa.message. Only values that really differ between deployments are properties: the retry back-off, the time after which a send counts as stuck, the poll interval, the mail body cap, the SMTP pool’s idle cut-off and messages per connection, and the mail fetch’s batch and lease are constants in the code. Every instance with message-starter sends: the delivery loop and the stuck-send sweep always run.

softa: message: quota: mail-monthly-default: 10000 # monthly ceiling for buckets with no TenantMessageQuota row; unset = unlimited sms-monthly-default: 10000 mail-daily-default: 2000 # daily cap for buckets with no TenantMessageQuota row; unset = unlimited sms-daily-default: 2000 dlq: topic: dev_demo_message_dlq # unset = broker-poison archiving disabled max-redeliver: 2 # broker nacks before dead-lettering alert: recipients: [email protected] # comma-separated; empty = no alert mail mail: debug: false # Jakarta Mail protocol debug, sends and fetches — never enable in prod (leaks AUTH) send-concurrency: 4 # mails one instance sends in parallel (each worker holds an SMTP connection) block-private-tenant-hosts: true # refuse a tenant's mail server on an address inside the deployment (multi-tenant only) transport: # connect + read at most 2m30s, neither zero (checked at startup) connection-timeout: 5s # SMTP/IMAP/POP3 connect timeout read-timeout: 30s # SMTP/IMAP/POP3 read timeout sms: send-concurrency: 10 # SMS one instance sends in parallel transport: # same limit as mail connection-timeout: 5s # HTTPS RestClient connect timeout read-timeout: 30s # HTTPS RestClient read timeout

Sending itself uses no Pulsar topic. message-starter consumes only two optional topics: cron-task drives the scheduled mail fetch, and softa.message.dlq.topic collects other consumers’ poison messages into the dead-letter table.

mq: topics: cron-task: topic: dev_demo_cron_task mail-fetch-sub: dev_demo_cron_task_mail_fetch_sub

Enabling and disabling

Templates, send servers, receive servers, SMS providers, country routes and template bindings can all be disabled: a disabled row is no longer picked as a default and takes no part in country routing, and a disabled template is not found by code; but it is not deleted, so rows that send records refer to are still there. A disabled configuration is still used where it is named by id: the serverConfigId / providerConfigId a caller gives, a template’s preferred server, and the replay of a prepared record. Each admin page has two tabs, Active and All; disabled rows are under All.

How active control is implemented

These ten models (MailTemplate / PlatformMailTemplate, MailSendServerConfig / PlatformMailSendServer, MailReceiveServerConfig / PlatformMailReceiveServer, SmsTemplate, SmsProviderConfig, SmsProviderRegion, SmsTemplateProviderBinding) declare @Model(activeControl = true): WhereBuilder adds active = true to every FlexQuery read, so resolution, dispatch and list filtering agree, and a newly written query cannot miss it. The All tab uses active IN (true, false), which names the field and so suppresses the automatic condition. Reads that must reach disabled rows use FilterControl.bypassActiveControl(): the editor tools (resolveAny / findAnyByCode, so a template can be previewed and its variables extracted before it is enabled) and demoting a default (demoteOtherDefaults: a disabled row it skipped would come back as a second default when re-enabled). Reads by id need no bypass: getById never carries the filter, so the server or provider a caller or template names, and the replay of a prepared record, are still found after the config is disabled, and an in-flight retry does not turn into CONFIG_NOT_RESOLVABLE because of it.

Encrypting sensitive fields

The passwords of mail send and receive servers (in the platform’s tables and the tenants’ alike) are declared as encrypted fields (encrypted = true): they are encrypted when stored, fully masked when read through the API, and the scanner syncs this flag to SysField. So are the SMS provider’s apiKey and apiSecret. A value already stored in plaintext is still read as it is (each read logs a WARN naming the rows to fix); fill it in again and save it once on the platform’s provider page and it is encrypted — see the field metadata encrypted attribute.

Upgrade notes

Upgrading to the release that splits the platform’s and the tenants’ tables, the deploying application moves data with release scripts before and after the new jar starts (zingkey-hcm’s are Release-20261113/20261111-message-split-by-owner).

  • Before the new jar starts (old jar stopped):
    • Create the five Platform* tables from their tenant tables, without tenant_id, and move the -1 rows across with their ids. Templates move only for the codes that become the platform’s; a -1 row with any other code is the platform tenant’s own tenant template and stays.
    • Delete the tenants’ rows of the four SMS config tables.
    • Move the moved rows’ seed bindings, and their attachments’ file_record.model_name, along.
    • Add mail_send_record.server_owner and backfill it from the table each record’s server is in.
    • None of this can wait for the scanner: the new jar reads only the Platform* tables and replays a prepared record’s server by server_owner, and while the SMS tables hold tenant rows the scanner’s unique keys fail.
  • After the new jar starts: delete the tenants’ templates that use a platform code, and user.contact-reset.
  • Other changes: password resets and the three security notices are sent with PLATFORM scope; the platform’s pages are on the new models and a tenant’s send log is TenantMailSendRecord, with role grants migrated to match; receiving no longer falls back to the platform’s receive servers; the new property softa.message.mail.block-private-tenant-hosts (default true) is set to false where tenants’ servers really are on an internal network.
Last updated on