Four Languages, One SMS Sandbox: Design Decisions and Trade-offs in SMSPit
Testing anything that sends SMS is awkward. You need real phone numbers, a paid provider account, network access and live credentials, and then someone has to look at a phone to confirm the message arrived. SMSPit is my answer: a self-hosted SMS sandbox. You point your application at it instead of your SMS provider, and every outgoing message is captured in a dashboard instead of being delivered. It can also pull one-time codes out of messages, replay a send, and pretend to be Vonage, AWS SNS or MessageBird so you do not have to change your SDK.
This post is not a feature tour. SMSPit is a young project (created in July 2026, 6 stars at the time of writing), so I have no adoption story to tell. What it does have is a deliberately split architecture, five services in four languages, and a set of design decisions I can show in real code. I want to go through them, including the places where the architecture runs ahead of what the tool needs and the gaps the project's own documentation admits to.
Scope note: everything below describes the repository at commita3d6f37(25 July 2026). I read the source and the project's own docs. I did not run the full stack: the project's changelog saysdocker compose upwas never run in the environment it was built in, and I did not run it either.
1. The shape of the system
| Service | Language | Job |
|---|---|---|
| gateway | Go (chi) | The single public entry point: reverse proxy, API-key check, per-tenant rate limit |
| auth-service | Laravel | API keys, organizations, teams; owns every database migration |
| sms-service | NestJS | Captures messages, serves the REST API and WebSocket, hosts the provider adapters |
| ai-service | FastAPI | OTP extraction, message category, spam score |
| worker | Go | Consumes a Redis Stream and classifies messages |
| dashboard | React | The UI, over REST and WebSocket |
A captured message follows this path. The gateway checks the API key, the NestJS service calls the AI service, saves the message to PostgreSQL, pushes it to the dashboard over WebSocket, and publishes a job to a Redis Stream, all before it answers the client:
client ──> gateway (key check + rate limit)
│
▼
sms-service ──> ai-service (sync, 2 s timeout, may return nothing)
│
├──> PostgreSQL (status = captured)
├──> WebSocket (live update to dashboards)
└──> Redis Stream (job for the worker)
Two things about that diagram are easy to miss. The AI service has no route through the gateway; only sms-service and worker can call it. And the worker is not a second source of truth. Per the project's own docs, it classifies each message and logs the result, but it never writes anything back. I come back to that in section 7.
2. A gateway that is only a door
The Go gateway is small on purpose. Its job is to be the one place that faces the network, and its core is Go's standard reverse proxy with a path rewrite, trace propagation and a JSON error for a dead upstream:
proxy := httputil.NewSingleHostReverseProxy(targetURL)
proxy.Transport = otelhttp.NewTransport(http.DefaultTransport) // carries the trace context upstream
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
w.WriteHeader(http.StatusBadGateway)
w.Write([]byte(`{"code":"BAD_GATEWAY","message":"upstream service unavailable","details":null}`))
}
The most instructive lines in the whole gateway are comments, because each one records a bug that only appeared once the services were wired together:
- Duplicate CORS headers. The backend sets its own CORS headers for when it is called directly, and the gateway sets them too. A proxied response then carried two
Access-Control-Allow-Originvalues, which browsers reject. The fix is to strip everyaccess-control-*header from the upstream response and let the gateway be the single source of truth. - CORS before auth. A browser's preflight request deliberately omits the
Authorizationheader. If the key check ran first, it would answer every preflight with a 401 that has no CORS headers, and the browser would block the real request. So the CORS middleware is registered before the auth middleware. - A route that was never wired. A QA pass found that every provider-adapter endpoint worked against
sms-servicedirectly but returned 404 through the gateway, because the/providers/*route did not exist. Since the adapters themselves worked, nothing insidesms-servicecould have flagged it. Only a pass through the real entry point caught it. - WebSockets cannot send an Authorization header. Browsers do not let you set one on the handshake, so the WebSocket route is unguarded at the gateway and authenticates with a
?token=query parameter at thesms-servicelayer.
The common thread: in a multi-service system, the seams between services generate their own bugs, and they hide from unit tests.
3. API keys: a lookup id plus a secret you only see once
Clients authenticate with Authorization: Bearer <key>.<secret>. The key is a non-secret lookup identifier; the secret is random, shown exactly once, and stored only as a hash:
// auth-service: creating a key
$key = 'sms_live_'.bin2hex(random_bytes(8));
$secret = bin2hex(random_bytes(24));
ApiKey::create([
'key' => $key,
'secret_hash' => Hash::make($secret), // only the hash is persisted
// ... name, owner_id, org_id, scopes
]);
// response: "key": "{$key}.{$secret}" // the only time the secret is visible
// auth-service: validating a request
[$lookupKey, $secret] = explode('.', $token, 2);
$apiKey = ApiKey::where('key', $lookupKey)->first();
if (! $apiKey || $apiKey->revoked_at !== null || ! Hash::check($secret, $apiKey->secret_hash)) {
return response()->json(['code' => 'UNAUTHORIZED', /* ... */], 401);
}
Splitting the token this way means a database lookup by an indexed, non-secret column, then one hash comparison, so you never scan or hash against every key. Revocation sets a revoked_at timestamp rather than deleting the row, and rotation creates a replacement with the same name, owner, org and scopes, then revokes the original. That keeps an audit trail and makes both operations safe to retry.
There is a cost worth naming. Per the docs, the gateway validates the key against auth-service, and sms-service validates it again itself as defence in depth. Every authenticated request therefore costs two round trips to the auth service, and each validation also writes a last_used_at timestamp. Two details in the gateway's validation client are also worth knowing: it uses Go's default HTTP client, which has no timeout, and an unreachable auth service is reported to the caller as "Invalid or revoked API key". The system fails closed, which is right, but the message hides the real cause and a hung auth service would hold gateway requests open.
4. Degrade, never fail the capture
The rule I am happiest with: optional infrastructure must never turn a successful capture into an error. The AI service is optional, and so is Redis. Both are wrapped so that a failure becomes "no value", not a 5xx:
// ai-client.ts
const REQUEST_TIMEOUT_MS = 2000;
private async post<T>(path: string, message: string): Promise<T | null> {
const baseUrl = this.config.get<string>('AI_SERVICE_URL');
if (!baseUrl) return null; // not configured: skip, don't fail
try {
const response = await fetch(`${baseUrl}${path}`, {
method: 'POST',
body: JSON.stringify({ message }),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
if (!response.ok) return null;
return (await response.json()) as T;
} catch (error) {
this.logger.warn(`ai-service unreachable for ${path}`);
return null; // down or slow: degrade
}
}
// messages.service.ts: the three calls run in parallel
const [otp, category, isSpam] = await Promise.all([
this.aiClient.detectOtp(dto.message),
this.aiClient.classify(dto.message),
this.aiClient.detectSpam(dto.message),
]);
Running the three calls in parallel with a 2-second cap each means a hung AI service adds at most about two seconds to a capture, not six. The queue publisher follows the same philosophy: the Redis client is configured with retryStrategy: () => null so it does not sit retrying a dead server inside a request, and a failed stream publish is logged and swallowed. The trade-off is explicit: if Redis is down, the message is saved and shown, but no job is queued for it. For a development sandbox that is the right call. For a system where the queue carried billing events, it would be the wrong one.
5. Pretending to be someone else's API
The feature that makes the sandbox usable without code changes is provider emulation. POST /providers/vonage/sms/json accepts a Vonage-shaped request and returns a Vonage-shaped response, so an app already using that SDK only changes a base URL:
@Controller('providers/vonage')
export class VonageController {
@Post('sms/json')
@HttpCode(HttpStatus.OK)
async send(@Body() dto: VonageSendDto) {
const message = await this.messagesService.create(
{ to: dto.to, from: dto.from, message: dto.text },
null, // no org: adapters have no SMSPit identity
);
// status "0" is Vonage's own success code; SDKs branch on it
return { 'message-count': '1', messages: [{ to: message.to, 'message-id': message.id, status: '0' }] };
}
}
This design forces a real trade-off, and the docs state it plainly. The adapters must look exactly like the real provider's unauthenticated wire format, so requiring an SMSPit API key on top would break the SDK. The consequence is that /providers/* is not authenticated and not rate limited, and every message captured that way lands in the "ungrouped" bucket, where a missing org is its own bucket, not a wildcard. The AWS SNS adapter is the awkward one: it speaks a form-encoded query API and returns XML errors, so it reads the raw body instead of using the validation pipeline every other endpoint uses. The project's security notes record that it originally checked only that the fields were present and was then hand-patched to enforce type and length limits (a phone number of at most 32 characters, a message of at most 1,600).
6. One database, one migration owner
The textbook rule is a database per service. SMSPit deliberately does not follow it. There is one PostgreSQL instance, auth-service (Laravel) is the only service that runs migrations, and the other services connect as plain SQL clients to the tables they use. The architecture doc gives the reasoning: one consistent migration history and one tool (php artisan migrate) beats coordinating migrations across Laravel, an ORM in the NestJS service and another in the Python service, for a self-hosted dev and test tool. I think that is a defensible call, and the part I like is that it is written down as a decision with a reason. The cost is that the "no service reaches into another's internals" boundary does not hold at the data layer, and a schema change in one service's table is a change in the auth service's repository.
7. Where the design runs ahead of the need
Reading the project critically, three things stand out.
- The "AI" service is rules. The changelog describes OTP detection as regex-based, classification as rule-based and spam detection as keyword and heuristic scoring. That is reasonable and cheap, and it works. But it is a good example of a service boundary drawn for a future that has not arrived. Today those rules could be a module inside
sms-service. A separate Python service earns its place when a real model needs to live there. - The worker demonstrates, it does not deliver. The docs say so outright: it consumes the stream with a consumer group (
XREADGROUPandXACK), calls the AI service, records a metric and a trace span, and logs. It does not write results back, and it is not a retry pipeline. The user-visible tags all come from the synchronous path. That is honest, but it means a whole deployable exists to prove a pattern. - Four backend languages for a dev tool. Each choice has a local justification: Go for a small, fast proxy, Laravel for quick organizations and policies, NestJS for WebSockets and DTO validation. Together they mean four toolchains, five backend dependency manifests and five services to run for anyone self-hosting it. If I were optimizing for adoption instead of for learning and range, I would collapse this.
8. What the project admits is unfinished
The changelog and security notes are more candid than most READMEs, and I want to repeat their open items:
- The full stack has not been verified with a real
docker compose up, nor a real Kubernetes or Helm install. The release was verified by equivalent means (host builds and real processes). The first real deployment should be treated as the test. - Key management is unauthenticated. Creating, revoking and rotating keys requires no key, because the first key cannot require one. Anyone who can reach the auth service can mint keys, and the gateway forwards
/auth/*unguarded. The security notes list this as a known finding that needs a proper bootstrap credential. - The SDKs are not published to Packagist, pkg.go.dev, npm or PyPI yet.
- The rate limiter is simple. It is a fixed one-minute window held in the gateway's memory, 300 requests per tenant by default. A fixed window allows a burst of up to twice the limit across a window boundary, each gateway replica keeps its own counters, and I did not find any code that evicts old tenant entries.
What I would take from this
- Draw service boundaries for today's need. A boundary you can name a reason for (an independent scaling profile, a different team, a different runtime requirement) is worth its cost. A boundary drawn for a hypothetical future is a deployable you now maintain.
- Make optional dependencies degrade. Give every optional call a timeout and a "no value" result, and decide in advance what the system does without it.
- Write the trade-off down next to the decision. The shared database, the unauthenticated adapters and the demo-only worker are all fine choices because the repository says why they were made.
- Test the seams. The missing gateway route and the double CORS header are integration problems that no single service's tests can see. An end-to-end pass through the real entry point is not optional.
- Trust headers only where you control the hop. If a downstream service relies on identity headers set by an upstream one, make the upstream clear them first, every time, not only when it has a value to set.
References
- SMSPit repository: github.com/jmrashed/SMSPit
- Architecture overview, request flow and database-migration decision: docs/architecture.md
- Gateway routes and identity headers: docs/gateway.md
- Security notes, key rotation and the unauthenticated key-management finding: docs/security.md
- Rate limiting behaviour: docs/rate-limiting.md
- Worker behaviour and limits: docs/worker.md
- Known gaps and release history: CHANGELOG.md
- Gateway reverse proxy, CORS handling and routes: proxy.go, router.go
- Key validation and rate limiter: auth/client.go, ratelimit.go
- API key creation and validation (Laravel): ApiKeyController.php, ValidateApiKey.php
- Capture path, AI client and queue publisher (NestJS): messages.service.ts, ai-client.ts, queue-publisher.ts
- Vonage adapter: vonage.controller.ts
- Go documentation, httputil.ReverseProxy: pkg.go.dev/net/http/httputil
- MDN, preflight request: developer.mozilla.org
- MDN, AbortSignal.timeout(): developer.mozilla.org
- Redis Streams: redis.io/docs/latest/develop/data-types/streams