Introducing a new way to review your PRs.

Read the announcement

ndolestudio / httpsms

Send and receive SMS messages using your Android phone programmatically via a simple HTTP API with end to end encryption supported.

View on GitHub

22 documents · Updated Nov 18, 2026

docs / sms-message-lifecycle

SMS message lifecycle

HTTPSMS uses a server-side message record as the shared point for API clients, Android phones, and delivery events. An outbound message moves from an API request to a phone notification, then to the phone's SMS service and its final delivery state. An inbound message starts at the phone and ends as a stored received message that other parts of the platform can show or act on. This page is a child view of the messaging platform.

Lifecycle model

The lifecycle has two main paths. Outbound work uses events and a phone notification so the API request can finish before the phone sends the SMS. Inbound work uses the Android app to forward a phone event to the API.

Outbound message path

An outbound message is first accepted and stored as pending. The phone must claim it before the Android app can send it. A requested send time or bulk-send position can delay the phone notification without changing this message path. The message.phone.sending, message.phone.sent, and message.phone.delivered events then move the record through device-side states.

This diagram shows the main path and its alternate outcomes.

flowchart LR
    A[Send API request] --> B[Store message as pending]
    B --> C[Schedule phone notification]
    C --> D[Send push notification]
    D --> E[Phone claims message]
    E --> F[Message is sending]
    F --> G[Android SMS service]
    G --> H[Sent callback]
    H --> I[Message is sent]
    I --> J[Delivered callback]
    J --> K[Message is delivered]
    G --> L[Failed callback]
    L --> M[Message is failed]
    D --> N[Notification failure]
    N --> M
    E --> O[Expiry check]
    O --> P[Message is expired]
    P --> C

References: api/…/message_handler.go• L51-67 api/…/message_service.go• L461-504 api/…/phone_notification_listener.go• L35-100 api/…/message_listener.go• L34-43

Inbound message path

The Android app watches the phone's SMS and MMS events. It checks that the SIM is active and that the user is logged in, queues the payload until network access is available, and posts it to the receive API. The API stores the message as received and publishes an event for thread and notification work.

This diagram shows how a phone event becomes platform data.

sequenceDiagram
    participant P as Android phone
    participant W as Android work queue
    participant A as Receive API
    participant S as Message service
    participant D as Event dispatcher
    participant DB as Message store

    P->>W: Capture SMS or MMS
    W->>A: POST /v1/messages/receive
    A->>S: Validate and accept payload
    S->>D: Publish message.phone.received
    S->>DB: Store message as received
    D-->>A: Event consumers update views and alerts

References: android/…/ReceivedReceiver.kt• L27-61 android/…/ReceivedReceiver.kt• L128-226 api/…/message_handler.go• L327-374 api/…/message_service.go• L319-363

Message states

The message record uses one status to describe the latest known state. scheduled describes deferred work, while sent means the phone sent the message and delivered means the phone received a delivery report.

StatusMeaningUsual next state
pendingThe API stored the message and it is waiting for phone work.sending, scheduled, or expired
scheduledA phone notification or send time is scheduled.sending, expired, or delivered
sendingThe phone claimed the message and is trying to send it.sent, delivered, failed, or expired
sentThe phone reported that the SMS service sent it.delivered
deliveredThe phone reported delivery to the contact.Terminal
receivedThe platform stored a message that arrived at the phone.Terminal for inbound SMS
failedThe phone or notification path reported a send failure.Terminal
expiredThe phone did not claim or complete the work before the expiry check.Retry or terminal

References: api/…/message.go• L24-54 api/…/message.go• L159-224 api/…/message_service.go• L662-769

API and service boundary

The API separates request checks from message work. Handlers check the request, account entitlement, and phone ownership before the message service creates the record or accepts a phone event.

Outbound request boundary

The authenticated client sends POST /v1/messages/send with the source phone, destination phone, content, and optional attachments or send time. The handler validates the request and billing entitlement, then returns the stored message after the service has queued its event. Bulk and scheduled entry points use the same service path; see bulk and scheduled messaging.

The optional request_id links a client request to its message record. Attachments make the outbound payload an MMS at the phone, while the message record still follows the same status path.

References: api/…/message_handler.go• L51-59 api/…/message_handler.go• L69-112 api/…/message_send_request.go• L14-61 api/…/message_service.go• L446-504

Phone event boundary

The Android app reports SENT, DELIVERED, or FAILED through POST /v1/messages/:messageID/events. The API checks the message owner against the phone API key before the service accepts the event. The service turns the event into a platform event and a listener applies the matching status change.

The phone also uses GET /v1/messages/outstanding to claim a message. The claim only accepts a message in pending, scheduled, or expired state, and it changes the record to sending as part of the claim. This prevents two phone workers from taking the same outstanding message at the same time.

References: api/…/message_handler.go• L61-67 api/…/message_handler.go• L174-219 api/…/message_handler.go• L265-325 api/…/gorm_message_repository.go• L244-278

Inbound request boundary

The Android app sends POST /v1/messages/receive with the phone number, contact number, content, SIM, event time, encryption flag, and optional MMS attachments. The handler checks the payload, account limits, and phone API key before the service accepts it.

The service uploads received attachments before it creates the stored message. It publishes message.phone.received with the message data, then stores a mobile-originated message with status received. Thread and notification consumers use the event without changing the inbound message's terminal status.

References: api/…/message_receive_request.go• L14-73 api/…/message_handler.go• L327-374 api/…/message_service.go• L319-363 api/…/message_service.go• L572-603

Thread summary boundary

Each message event also keeps the conversation summary aligned with the latest message. A message thread is the pair of an owner phone and a contact for one user. It stores the last message identity, content, time, and status, plus read and archive state; see message threads and search.

When a new inbound message reaches an archived thread, the thread service checks the owner's unarchive setting and can reopen the thread. When a message is removed, the service either restores the prior message as the thread summary or removes the empty thread. These updates do not change the message's own delivery status.

Thread reads stay scoped to the requesting user. Contact details are optional enrichment; the service loads them only when requested and only after the thread query succeeds. If the contact lookup fails, the service keeps the thread results and omits the extra contact data. See contacts and conversation recipients for the contact model. Activity updates also keep message summary fields separate from unread and archive controls, so a lifecycle event cannot reset those user-facing states.

References: api/…/message_thread.go• L9-35 api/…/message_thread_service.go• L87-140 api/…/message_thread_service.go• L169-206 api/…/message_thread_service_contacts_test.go• L80-159 api/…/message_thread_handler_test.go• L98-157 api/…/gorm_message_thread_repository_test.go• L142-231

Event and persistence model

Events connect the message record to work that must happen outside the request. The event dispatcher validates each CloudEvent and sends it through the queue to subscribed listeners. Message, thread, and phone-notification listeners can therefore react to the same lifecycle event without making the API handler know every downstream action.

Outbound event chain

message.api.sent starts the outbound path after the message is stored. The phone notification listener creates a phone notification and emits the scheduled and send events. The send event reaches the FCM service, which sends the message ID to the Android app.

The message listener handles the later notification and phone events. The service can delay the notification until a requested send time or pace it by a bulk-send position. A notification-sent event records the send attempt without moving a scheduled message back to pending. The thread listener handles the same state events to keep conversation summaries aligned; read and push behavior has a separate view in push delivery and read receipts.

References: api/…/message_service.go• L461-503 api/…/phone_notification_listener.go• L23-100 api/…/phone_notification_service.go• L128-169 api/…/message_listener.go• L34-43 api/…/message_thread_listener.go• L35-47 api/…/message_service_test.go• L39-138

Message record

The message record keeps the identity, two phone numbers, content, type, current status, and event times. It also keeps the retry count and the reason for a failed send. mobile-terminated identifies outbound SMS or MMS, while mobile-originated identifies a message received by the phone.

The repository supports both lifecycle writes and client reads. API clients can fetch one message, list a conversation, search by content or status, or fetch an outstanding message for a phone. Conversation grouping and search details are covered in message threads and search.

References: api/…/message.go• L10-22 api/…/message.go• L85-122 api/…/message_repository.go• L10-43 api/…/gorm_message_repository.go• L202-241

Phone notification record

A phone notification is the server-side record for one push attempt to one registered phone. It links a message to a phone and has its own pending, sent, or failed status. This status describes push delivery to the Android app, not SMS delivery to the contact.

When the push succeeds, the notification event starts the message expiry timer and increases the message's send-attempt count. When the push fails, the message listener records a message send failure. This distinction helps an engineer tell a phone connectivity problem from a carrier delivery problem; phone registration and availability are described in phone connectivity when that page is available.

The notification-sent handling preserves the message's current lifecycle state while it records the attempt. It does not roll a scheduled message back to pending, which keeps the requested send time visible to later expiry and retry work.

References: api/…/phone_notification.go• L9-31 api/…/phone_notification_service.go• L128-169 api/…/phone_notification_service.go• L330-374 api/…/message_listener.go• L144-206 api/…/message_service_test.go• L18-61

Phone delivery path

The Android app is the SMS endpoint. The server does not use a carrier API for the final send; it asks the registered phone to fetch the message and the Android SMS service uses the selected SIM.

Push handoff

The server sends an FCM data message with the message ID. The Android app turns that push into a network-constrained background job. The job calls the outstanding-message API, which marks the message as sending and returns its content, destination, SIM, encryption flag, and attachments.

This handoff has two separate acknowledgements. FCM success means the push was sent to the phone. The later SENT or DELIVERED event comes from the Android SMS service and describes the SMS itself.

References: api/…/phone_notification_service.go• L128-169 api/…/phone_notification_service.go• L281-300 android/…/FirebaseMessagingService.kt• L21-40 android/…/FirebaseMessagingService.kt• L134-180 api/…/message_service.go• L73-106

Android SMS handoff

After the phone claims the message, the Android worker checks login state, SIM activity, and the encryption key when needed. It decrypts encrypted content only on the phone. It then sends plain SMS, multipart SMS, or MMS through the selected SIM.

The Android SMS service gives the worker separate callbacks for send and carrier delivery. Multipart messages use the base message ID for the final callback, so message segments do not become separate platform messages.

References: android/…/FirebaseMessagingService.kt• L141-179 android/…/FirebaseMessagingService.kt• L197-317 android/…/FirebaseMessagingService.kt• L319-408 android/…/SmsManagerService.kt• L43-84

Delivery callbacks

The Android sent receiver maps the SMS result to SENT or FAILED. The delivered receiver maps the carrier delivery result to DELIVERED or FAILED. Both receivers wait for network access before posting the event to the API, and they retry the background work when the post fails.

The API listeners then update the message record. A sent event records send time and duration. A delivered event records delivery time and can complete the message even when the sent callback was delayed. A failed event stores the phone error as the failure reason.

References: android/…/SentReceiver.kt• L19-31 android/…/SentReceiver.kt• L54-134 android/…/DeliveredReceiver.kt• L18-109 api/…/message_service.go• L365-444 api/…/message_service.go• L686-769

Expiry and retry

Expiry covers work that the phone did not complete within the phone's message expiry period. The system checks the message after the push is sent, marks unfinished work as expired, and may send it again when the retry limit allows.

Expiry checks

The notification-sent event schedules a delayed expiry check. When the check runs, it reloads the message and does nothing if the record is already sent, delivered, failed, or received. For unfinished outbound states, it emits message.send.expired.

This design makes expiry safe when events arrive late. A late delivery event can still move an eligible message to delivered, while an expiry check for a deleted message is ignored.

References: api/…/message_listener.go• L173-227 api/…/message_service.go• L772-900 api/…/message_service.go• L911-955

Retry boundary

The expired event stores the expired state and checks send_attempt_count against max_send_attempts. If attempts remain, it emits message.send.retry, which schedules a new phone notification. If no attempts remain, expired is the terminal state for that send.

An explicit phone failure does not enter this expiry retry path. It records failed with the reported reason, so operators can distinguish a device or carrier error from a message that never reached the phone in time.

References: api/…/message.go• L144-152 api/…/message_service.go• L816-862 api/…/phone_notification_listener.go• L75-100 api/…/message_send_expired_event.go• L10-26

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the status names and allowed transitions aligned between api/…/message.go, the message service handlers, the Android event names, and any client status filters.
  • Keep the message ID format shared by FCM data, the outstanding-message claim, and Android multipart callbacks. A segment ID must not create a second message event.
  • Keep the payload fields aligned across event structs, listeners, and Android request builders. In particular, preserve the user ID, owner phone, contact phone, SIM, timestamp, and encryption flag.
  • When changing push expiry or retry rules, update both the phone notification timing and the message attempt count. These values control whether an expired message is retried or becomes terminal.
  • When changing inbound attachment handling, keep the temporary phone files, base64 receive payload, uploaded URLs, and stored message attachments consistent.
  • When changing phone ownership checks, preserve the match between the message owner and the phone API key for both outstanding claims and status events.
  • When changing thread event updates, keep the message timestamp, last-message ID, status, unread watermark, and archive behavior aligned. A stale event can otherwise overwrite the visible conversation summary.
  • When changing thread reads, preserve the contract between is_archived, is_read, owner, query, skip, limit, and optional contact details across query sanitization, validation, service parameters, and the thread response.
  • Keep thread activity updates separate from unread and archive updates. Conflict handling must increase unread counts without replacing archive state, and lifecycle activity must not overwrite user status changes.
  • Keep contact enrichment optional and best effort. A contact provider error must not hide valid thread results, while a failed thread query must not trigger a contact lookup.
  • Keep scheduled send times and bulk-send pacing in the delay calculation. A notification-sent event must record the attempt without restoring an older message state.

Important failure modes

TriggerConsequenceGuard
The phone has no FCM token or FCM rejects the send.The phone notification becomes failed and the message is recorded as failed before the SMS service runs.Phone enrollment must keep the FCM token current.
The phone is logged out or its SIM is inactive when a push arrives.The Android worker stops and reports a failed message when outgoing messages are disabled.The worker checks login and SIM status before claiming SMS work.
An encrypted message reaches a phone without the matching key.The phone cannot decrypt the content and reports a failed message.Configure the same encryption key on the Android app before sending encrypted content.
The phone does not claim the message before the expiry check.The message becomes expired and is retried only if attempts remain.The expiry check reloads current state and compares the attempt count to the configured limit.
A multipart callback uses a segment ID.The Android receiver ignores that segment and waits for the base message callback.Use the base message ID for the final multipart part.
The phone cannot reach the API after a callback.The local callback is not recorded until the network-constrained worker succeeds.Android WorkManager retries callback posts when the request fails.
An inbound MMS attachment is missing from the phone cache.The message can be stored without that attachment.The receive worker checks each temporary file before encoding it.
A lifecycle event has an older timestamp or a different last-message ID than the thread.The thread summary can move backward or update the wrong message state.The thread service compares the event time and last-message ID before applying the activity update.
A thread query has invalid paging, owner, archive, or contact options.The API rejects the request instead of returning a partial or wrongly scoped thread list.Query input is sanitized and validated before the service loads user-owned threads.
Unread filtering runs after thread pagination.A page can contain too few or the wrong threads for an unread-only request.The repository applies the unread condition before LIMIT and OFFSET.
A lifecycle activity update includes unread or archive fields.A message event can clear a user's unread count or archive choice.Activity updates write only the message summary fields; separate status updates own unread and archive fields.
Contact enrichment fails while a thread list is valid.The API can lose usable thread data if the optional contact provider error is returned as the main result.The service logs the lookup error and returns threads without contact details.
A notification-sent event uses an older message state.A scheduled message can be restored to pending and follow the wrong expiry path.Notification handling preserves the current state while recording the send attempt.

Key files

FileWhy to read it
api/…/message_handler.goMaps public send, receive, outstanding, and phone-event requests to the message service.
api/…/message_service.goDefines message creation, event handling, persistence changes, expiry, and retry decisions.
api/…/message.goDefines message types, statuses, timestamps, and state-changing rules.
api/…/event_dispatcher_service.goExplains the queued event boundary and listener fan-out used by the lifecycle.
api/…/message_listener.goConnects lifecycle events to message status updates.
api/…/phone_notification_listener.goConnects API and retry events to push notification scheduling and sending.
api/…/phone_notification_service.goDescribes the push handoff and its own notification outcomes.
api/…/gorm_message_repository.goShows how messages are claimed, stored, updated, and read from persistence.
api/…/message_thread.goDefines the conversation summary that lifecycle events update.
api/…/message_thread_service.goExplains how message events create or update threads and handle archive and delete effects.
api/…/message_thread_handler.goMaps thread list, archive/read update, and delete requests to the thread service.
api/…/message_thread_index_request.goDefines thread list filters and their default values before service use.
api/…/message_thread_handler_test.goPins user-scoped thread reads and the not-found boundary for missing threads.
api/…/gorm_message_thread_repository_test.goPins unread filtering order, unread count updates, and separation of message, archive, and unread fields.
api/…/message_thread_service_contacts_test.goShows optional contact enrichment and the best-effort behavior of contact lookup.
api/…/message_service_test.goPins scheduled and bulk-send delays and the notification attempt state contract.
api/…/message_handler_validator.goDefines the input and event contracts that protect send, receive, search, and callback boundaries.
android/…/FirebaseMessagingService.ktShows how a push becomes an Android send job and how the phone claims work.
android/…/ReceivedReceiver.ktShows how inbound SMS and MMS data enters the Android work queue.
android/…/SentReceiver.ktMaps Android send results to API events.
android/…/DeliveredReceiver.ktMaps Android delivery reports to API events.
android/…/HttpSmsApiService.ktDefines the Android HTTP calls for outstanding messages, receive requests, and status events.