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 / api-service-architecture

API service architecture

The Go API service exposes the httpSMS HTTP API and coordinates work between clients, phones, storage, queues, and external services. It keeps transport concerns at the edge, places product rules in services, and uses shared data and operational packages so both direct requests and asynchronous events follow the same system rules.

Service composition

The service is assembled as one Fiber application with a shared dependency container. The container connects route handlers to validators, product services, repositories, event listeners, caches, external clients, and telemetry before the process starts listening. The application serves versioned API routes under /v1 and also exposes health and API documentation endpoints. See api/main.go and api/…/container.go.

The main product areas are registered as route and event pairs. A route accepts a client action, while a listener handles work that can continue after the request or react to a phone, billing, webhook, or account event.

System areaMain responsibility
Messages and message threadsAccept, find, update, and track SMS work and its conversation view. See Messaging platform.
Phones and phone keysManage Android phone links and the keys that limit phone access. See Phone connectivity.
Contacts and heartbeatsStore contacts and monitor phone availability
Users and billingManage user state, plan limits, and usage-related actions
Webhooks and integrationsConnect message events with customer endpoints and third-party systems. See Integrations and automation.
Notifications and marketingSend email, push, websocket, or campaign updates

Dependency container

The dependency container is the composition root. A composition root is the place where the system chooses concrete resources and passes them into the objects that use them. It builds shared database connections and clients first, then builds repositories, services, handlers, and listeners from those resources. This keeps route registration and event subscription in one startup path instead of making each feature create its own dependencies. See api/…/container.go• L85-170.

The container also selects resource providers from the running environment. Contacts and heartbeat monitors can use either the main relational path or MongoDB. Attachments can use cloud storage or memory. The selection changes the resource behind a common boundary while leaving the higher product layer unchanged. Heartbeat monitor writes use the request context and a bounded database operation window, so cancellation and slow storage do not remain detached from the caller. See api/…/container.go• L944-981, api/…/container.go• L1667-1695, and api/…/gorm_heartbeat_monitor_repository.go• L48-88.

The Go module manifest defines the service's main boundary dependencies. They cover the HTTP server, relational and document storage, queues and cloud storage, external clients, and OpenTelemetry support. The lock data in api/go.sum keeps the selected module graph verifiable when these boundaries are built or changed. See api/go.mod#L1-L65 and api/go.sum#L386-L435.

References: api/main.go• L32-45 api/…/container.go• L85-170 api/…/container.go• L944-981 api/…/container.go• L1667-1695 api/…/gorm_heartbeat_monitor_repository.go• L48-88 api/go.mod• L1-65 api/go.sum• L386-435

Request boundaries

The HTTP boundary turns a Fiber request into a product action. Handlers bind transport data into request objects, pass it through validation, call a service, and map the result into a stable JSON response. They do not own the storage or external-system decisions that carry out the action. See api/…/handler.go and api/…/message_handler.go• L24-112.

The shared response shape gives clients a small set of predictable outcomes. Success responses carry a status, message, and optional data. Error responses use the same outer shape while adding field errors or access details when needed. This boundary lets product services report domain results without knowing how Fiber writes HTTP responses. See api/…/handler.go• L18-115 and api/…/response.go• L3-58.

Authentication boundary

Authentication is split into recognition and enforcement. Bearer authentication can place a Firebase identity in request context. API-key authentication can place a user or phone-key identity in the same context. The authenticated middleware then rejects a request when no usable identity is present. Route groups add the stricter phone-key check where an Android phone acts as the caller. See api/…/bearer_auth_middleware.go• L15-49, api/…/api_key_auth_middleware.go• L13-37, and api/…/authenticated_middlesare.go• L20-35.

The shared identity is an authentication context. Handlers use it to find the acting user and to check whether a phone-scoped key may act on a particular phone. This makes the same product service usable from a user request and from a phone request while keeping access checks at the transport edge. See api/…/handler.go• L124-162 and api/…/phone_api_key_auth_middleware.go• L13-35.

References: api/…/handler.go• L18-162 api/…/message_handler.go• L51-112 api/…/bearer_auth_middleware.go• L15-49 api/…/api_key_auth_middleware.go• L13-37 api/…/authenticated_middlesare.go• L20-35 api/…/phone_api_key_auth_middleware.go• L13-35 api/…/response.go• L3-58

Shared middleware

Application middleware applies cross-cutting rules before feature routes run. Compression reduces response size. CORS controls browser access. Request logging records the request result. OpenTelemetry starts the request trace. Authentication middleware makes known identities available. The health route is registered before this stack so a platform health check can remain simple and reliable. See api/…/container.go• L173-213.

Feature routes add the middleware they need. Most routes require an authenticated user. Phone-facing routes add phone-key authentication before the common authenticated check. This ordering lets authentication providers try to establish identity first and lets the final check decide whether the route may proceed. See api/…/container.go• L1744-1810.

References: api/…/container.go• L173-213 api/…/container.go• L1427-1443 api/…/container.go• L1744-1810

Persistence-facing layers

The persistence-facing layers separate product actions from storage choices. Services express product work. Repositories express access to users, phones, messages, contacts, billing data, webhooks, and related records. Entities define the business records shared by these layers. A repository interface gives the service layer a stable boundary even when the backing store changes. See api/…/repository.go• L9-23 and api/…/container.go• L799-981.

The service layer also coordinates work that is not a single database operation. For example, message work can use message storage, phone state, attachment storage, and event dispatch. Heartbeat work follows the same pattern: it stores a heartbeat, checks monitor state, schedules a later check, and emits phone status events when the state changes. This is why handlers call services rather than repositories directly: the service can preserve product rules while combining several resources. See api/…/container.go• L1653-1695 and api/…/heartbeat_service.go• L95-146.

The service has two relational database roles and a separate MongoDB option. The main relational connection supports core records and migrations. A dedicated relational connection supports heartbeat data when that path is selected. MongoDB is available for selected contact and heartbeat resources. Its database name comes from the URI, UUID values use a stable string form, and startup creates indexes for lookup and heartbeat retention. Redis supplies shared temporary data, while local caches support short-lived process data. See api/…/container.go• L256-427, api/…/container.go• L297-312, api/…/mongodb.go• L51-138, and api/…/cache.go• L8-12.

References: api/…/repository.go• L9-23 api/…/container.go• L256-427 api/…/container.go• L799-981 api/…/container.go• L1653-1695 api/…/heartbeat_service.go• L95-146 api/…/mongodb.go• L23-138 api/…/cache.go• L8-12 api/…/gorm_heartbeat_monitor_repository.go• L91-184

Event and queue boundary

The event system carries work between product areas and between request time and later processing. A service creates a CloudEvent that names the event type and carries its data. The event dispatcher can publish it to in-process listeners or place it on the configured push queue for an HTTP consumer. Listeners subscribe to event types during startup. See api/…/service.go• L17-29, api/…/event_dispatcher_service.go• L22-47, and api/…/event_dispatcher_service.go• L99-152.

This boundary supports the SMS model in which the API accepts work before the Android phone performs it. A request can store the message and dispatch a notification event. A later queue task or listener can notify the phone, process the result, and trigger follow-up work such as delivery, expiry, or webhook notification. Heartbeat monitoring uses the same boundary to schedule checks and report missed, offline, or recovered phones. The request-processing page describes the request lifecycle in more detail: API request processing. See api/…/heartbeat_service.go• L157-185 and api/…/heartbeat_service.go• L288-379.

The queue task targets the configured event consumer and carries the system API key needed for that internal call. If queue submission reaches its deadline, the dispatcher uses a local delayed publish as a fallback. This keeps the event model usable in a local or degraded environment while preserving the same event contract. See api/…/event_dispatcher_service.go• L63-103.

References: api/…/service.go• L17-29 api/…/event_dispatcher_service.go• L22-47 api/…/event_dispatcher_service.go• L63-103 api/…/event_dispatcher_service.go• L107-176 api/…/heartbeat_service.go• L157-185 api/…/heartbeat_service.go• L288-408 api/…/container.go• L1269-1295

Operational support

Operational packages make requests and background work observable. The telemetry interfaces provide structured logs and trace spans without binding feature code to one logging or tracing implementation. Request middleware starts the outer span. Handlers, services, repositories, caches, and outbound HTTP clients can add child spans and attach the same trace context to logs. Database logging also carries the active span into query messages and records query errors. MongoDB access uses the same trace path through its database monitor. See api/…/logger.go• L7-38, api/…/tracer.go• L15-37, api/…/otel_tracer.go• L27-69, api/…/gorm_logger.go• L30-54, and api/…/mongodb.go• L62-69.

The service exports a stable subset of spans instead of treating every span as equally useful. Normal traces use a stable hash of the trace ID for about 50% retention. Warnings and errors promote their span. Database spans over 200 milliseconds remain available, as do spans with explicit retention flags or truncated telemetry. Metrics exemplars use the same stable trace decision, which keeps trace-to-metric links consistent. See api/…/sampling_span_processor.go• L23-104 and api/…/container.go• L1919-2004.

Structured logs carry trace and span IDs when a span is present. Warning, error, and fatal logs mark the active span for retention, so an operational signal remains connected to the trace that produced it. See api/…/zerolog_logger.go• L19-110.

Outbound calls use named HTTP clients with tracing. Most clients also use a small retry layer. Webhooks and phone notification adapters use clients without transport-level retries so their services can apply their own delivery policy. Database, Redis, and MongoDB access also has telemetry hooks. These links allow one request or event to be followed across internal layers and external systems. See api/…/container.go• L1048-1093 and api/…/http_notification_sender_test.go• L84-182.

The service exposes /health for platform checks and serves generated API documentation through the final catch-all route. Startup may also run relational migrations and create MongoDB indexes. A missing or invalid required connection therefore prevents a healthy service from starting rather than leaving a partly wired application running. See api/…/container.go• L183-186, api/…/container.go• L270-294, api/…/mongodb.go• L51-88, and api/…/container.go• L1813-1827.

References: api/…/logger.go• L7-38 api/…/tracer.go• L15-37 api/…/otel_tracer.go• L27-69 api/…/gorm_logger.go• L30-54 api/…/mongodb.go• L51-88 api/…/sampling_span_processor.go• L23-104 api/…/zerolog_logger.go• L19-110 api/…/container.go• L1048-1093 api/…/container.go• L183-186 api/…/container.go• L270-294 api/…/container.go• L1813-1827

Change checklist

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

  • A new route feature needs both handler construction and route registration in the container. If it emits events, it also needs listener construction and subscription.
  • A new persistence option must preserve the repository interface and must be selected by the same container path as its resource connection.
  • A change to authentication context fields must be checked against API-key middleware, phone-key middleware, authenticated middleware, and handler authorization checks.
  • A change to an event type or payload must be checked against event creation, queue delivery, listener subscription, and the internal event endpoint contract.
  • A change to a response shape must be checked against both handler helpers and the generated API schema.
  • A change to an external client must preserve its named tracing path and its retry or no-retry policy.
  • A change to log severity or span retention rules must be checked against the span processor and the metric exemplar filter so operational signals keep their trace links.
  • A change to heartbeat storage operations must preserve request context propagation and the bounded database operation window.
  • A change to MongoDB UUID encoding, database naming, or index policy must be checked against all contact and heartbeat repository queries and startup readiness.
  • A change to the Go module version or checksum set must preserve the telemetry and storage instrumentation used by the service boundaries.

Important failure modes

TriggerConsequenceGuard
No valid user or phone identity reaches an authenticated routeThe request is rejected with 401 UnauthorizedKeep an identity provider before Authenticated middleware
A phone-scoped key targets a phone outside its contextThe request is denied even when the user is knownKeep phone ownership checks in the shared handler authorization path
The queue consumer or internal API key is wrongAsynchronous events cannot reach the event endpointKeep queue configuration and the system user contract aligned
A selected MongoDB or relational connection cannot startThe service fails during dependency setupCheck the selected backend, URI database name, and connection settings before deployment
MongoDB indexes are missing or use a changed field shapeContact and heartbeat reads can become slow or retention can failKeep index creation aligned with repository query fields and heartbeat timestamps
A database operation loses its request contextCancellation and timeout signals do not reach storagePass the bounded context into the database call
A heartbeat check is not scheduled after monitor state changesPhone offline or recovery events are delayed or missedKeep monitor updates and delayed event dispatch in the heartbeat service path
A warning or error does not mark its span for retentionThe log can exist without the trace needed to explain itKeep severity logging connected to the sampling retention flag
A catch-all documentation route is registered before feature routesRequests can resolve to documentation instead of the API featureRegister Swagger last

Key files

FileWhy to read it
api/main.goShows process startup and the application entry point
api/go.modDefines the main storage, queue, HTTP, and telemetry dependency groups
api/go.sumRecords the checksums for the resolved Go module graph
api/…/container.goShows dependency wiring, route registration, resource selection, listener setup, and telemetry provider setup
api/…/handler.goShows shared request context, authorization helpers, and response mapping
api/…/authenticated_middlesare.goShows the final access gate for protected routes
api/…/message_handler.goShows the transport boundary for a core SMS feature
api/…/event_dispatcher_service.goShows the synchronous, queued, and listener-based event boundary
api/…/heartbeat_service.goShows how persistence, delayed checks, phone state, and events combine for availability monitoring
api/…/repository.goShows the shared persistence contract and storage error boundary
api/…/gorm_heartbeat_monitor_repository.goShows context-aware persistence for phone availability monitoring
api/…/mongodb.goShows the alternate persistence connection, UUID boundary, telemetry hook, and index setup
api/…/cache.goShows the shared temporary-data contract
api/…/tracer.goShows the tracing boundary shared by HTTP and background work
api/…/sampling_span_processor.goShows which traces remain available for operational diagnosis
api/…/zerolog_logger.goShows the link between structured logs and trace retention