SMS8

Webhook vs polling for incoming SMS

Latency, reliability, code, signing, retries, idempotency, fault tolerance. The decision guide and runbook.

Part of the guide SMS API Documentation: Android SMS Gateway, OTP and Webhooks

On this page
  1. Key takeaways
  2. What is the difference, mechanically?
  3. How do they actually compare?
  4. When should I use polling?
  5. How do I set up a webhook with SMS8?
  6. What does the payload look like?
  7. How do I verify the signature?
  8. What about retries and idempotency?
  9. A clean polling implementation, for the cases that need it
  10. How do I combine the two safely?
  11. What does scale look like in practice?
  12. What does a production-grade queue handler look like?
  13. How do I test webhooks during development?
  14. What is the right default in production?
  15. Webhook security checklist
  16. Latency tracing: where does the time go?
  17. Why developers choose SMS8 for incoming SMS

Key takeaways

  • Default to webhooks. Lower latency, lower cost, scales for free.
  • Poll only when your receiver has no public endpoint (firewalls, dev laptops, batch ETL).
  • Sign and verify webhooks with HMAC-SHA256. Always.
  • Return 2xx within 10 seconds, even if you queue the work. SMS8 retries anything else.
  • Run a polling backstop at a slow interval so a missed webhook does not silently drop a message.

This is one of those choices that looks like a religious war in forum threads. It is not. There is a clear winner for most cases and a defensible loser for a small set of cases. The endpoints and payloads are in the SMS8 API documentation; for the bigger picture, see the complete Android SMS gateway guide. If you arrived here from the Claude Code MCP tutorial, this covers what happens after the agent sends and a reply arrives. SMS8 supports both, with signed webhooks retried for up to 30 days.

What is the difference, mechanically?

Webhook. SMS8 makes an HTTPS POST to your endpoint the moment a new SMS arrives. Push model. Your server sits idle until a message comes in.

Polling. Your server asks SMS8 every N seconds "any new messages since timestamp X?" Pull model. Your server runs a cron or a long-lived loop.

Both end up with the same data on your side. The question is who initiates the conversation and how often.

How do they actually compare?

DimensionWebhookPolling
Latency to receive an SMS1 to 3 seconds30 to 60 seconds (depends on interval)
API calls per day (no traffic)01,440 to 2,880
Requires public HTTPS endpointYesNo
Handles burst trafficNativelyCatches up on next poll
Survives endpoint downtimeYes, retried for up to 30 daysYes, polls when restored
Setup complexityMedium (signature verify)Low (one GET loop)
Rate-limit riskNoneMedium (if interval too tight)
Best for production user-facing flowsYesNo
Best for batch reporting / ETLNoYes

When should I use polling?

  • You are developing locally and do not want to expose your laptop with ngrok.
  • Your network sits behind a strict firewall that blocks inbound HTTPS.
  • You only care about replies once a day for a report.
  • You are building a quick prototype and want zero infra.
  • You are running a batch ETL that wakes up every 15 minutes anyway.

That is the entire list. Everywhere else, use webhooks.

How do I set up a webhook with SMS8?

Two ways: the Webhooks page in the dashboard (https://app.sms8.io/webhook.php), where you add the URL and pick the events, or the create_webhook tool in the SMS8 MCP server.

Each webhook gets its own signing secret. Store the secret server-side, never in client code. Treat it like a password.

What does the payload look like?

POST /sms-inbox
Content-Type: application/json
X-Signature: sha256=4f3a...
User-Agent: SMS8-Webhook/2.0

{
  "event": "messages",
  "timestamp": "2026-05-24T14:22:31+00:00",
  "userID": 42,
  "data": [
    {
      "ID": 128476,
      "number": "+15551234567",
      "message": "yes, confirmed",
      "deviceID": 42,
      "simSlot": 0
    }
  ]
}

How do I verify the signature?

PHP

$payload = file_get_contents('php://input');
$received = $_SERVER['HTTP_X_SIGNATURE'] ?? '';

// HMAC-SHA256 of the raw body, keyed with the webhook's signing secret
$expected = 'sha256=' . hash_hmac('sha256', $payload, $WEBHOOK_SECRET);
if (!hash_equals($expected, $received)) {
    http_response_code(401); exit('invalid signature');
}

$data = json_decode($payload, true);

Node

const crypto = require('crypto');
const received = req.headers['x-signature'] || '';

const expected = 'sha256=' + crypto.createHmac('sha256', WEBHOOK_SECRET)
                                   .update(req.rawBody).digest('hex');
if (received.length !== expected.length ||
    !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received))) {
  return res.status(401).send('invalid signature');
}

Python

import hmac, hashlib
from flask import request, abort

received = request.headers.get('X-Signature', '')
expected = 'sha256=' + hmac.new(WEBHOOK_SECRET.encode(), request.get_data(),
                                 hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, received):
    abort(401, 'invalid signature')

HMAC signature verification follows the same pattern as Stripe and GitHub webhooks. The general HMAC practice is documented in RFC 2104. The signature covers the raw body only, so pair it with the idempotency check below: a captured request that is re-sent later carries a message ID you have already processed.

What about retries and idempotency?

If your endpoint does not answer with a 2xx within 10 seconds, SMS8 tries again on a schedule that grows from a few minutes up to 30 days. Each attempt shows in the deliveries log. Each delivery sends the same message ID, so your handler must be idempotent. The simplest pattern is to use the message id as a primary key in a "processed events" table and rely on the database to reject duplicates.

// PHP, using MySQL
function handleWebhook(array $payload): int {
    try {
        $db->insert('processed_events', [
            'event_id' => $payload['data'][0]['ID'],
            'processed_at' => time(),
        ]); // PK is event_id, duplicate insert throws
    } catch (PDOException $e) {
        if ($e->errorInfo[1] == 1062) { // duplicate key
            return 200; // already processed
        }
        throw $e;
    }
    processMessage($payload);
    return 200;
}

Return 2xx fast. If the work is slow, push to a queue and respond immediately. SMS8 considers any response over 10 seconds a timeout, marks the delivery failed, and retries.

A clean polling implementation, for the cases that need it

# PHP cron, every 30 seconds via supervisor or systemd timer
$since = file_get_contents('last_seen.txt') ?: '1970-01-01T00:00:00Z';
$ch = curl_init('https://app.sms8.io/api/v1/messages/read');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ["X-Api-Key: $KEY", 'Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode(['direction' => 'inbound', 'since' => $since]),
    CURLOPT_RETURNTRANSFER => true,
]);
$msgs = json_decode(curl_exec($ch), true)['messages'] ?? [];
foreach ($msgs as $m) {
    processMessage($m);
}
if ($msgs) {
    file_put_contents('last_seen.txt', end($msgs)['createdAt']);
}
# Python long-polling loop
import requests, time, json, pathlib

last = pathlib.Path('last_seen.txt')
since = last.read_text() if last.exists() else '1970-01-01T00:00:00Z'

while True:
    r = requests.post(
        'https://app.sms8.io/api/v1/messages/read',
        headers={'X-Api-Key': API_KEY},
        json={'direction': 'inbound', 'since': since},
        timeout=10,
    )
    msgs = r.json().get('messages', [])
    for m in msgs:
        process_message(m)
    if msgs:
        since = msgs[-1]['createdAt']
        last.write_text(since)
    time.sleep(30)

How do I combine the two safely?

Run webhooks as primary and a slow polling backstop as secondary. The polling job runs every 5 minutes, asks "show me messages since 6 minutes ago that I have not seen", and dispatches them through the same idempotent handler. If a webhook succeeded, the polling no-ops. If a webhook failed (maybe your TLS cert just expired silently), the poller catches the gap.

The gaps this catches are boring ones: an expired TLS certificate, a DNS change, a load balancer config change. The backstop costs little: polling every 5 minutes is 288 API calls per day.

What does scale look like in practice?

Scale on the customer side is limited only by your endpoint's queue throughput. A slow handler tends to get rewritten sooner or later, because the 10-second timeout becomes a recurring incident. The "queue immediately, process async" pattern is not optional past a few hundred messages per day.

What does a production-grade queue handler look like?

This is the pattern we recommend, using Redis as the queue and a worker process to do the heavy lifting:

// PHP webhook receiver (returns within 50 ms)
$payload = file_get_contents('php://input');
// ... signature verify omitted for brevity ...
$event = json_decode($payload, true);

// Idempotency
$msgId = $event['data'][0]['ID'];
if ($redis->setnx("seen:{$msgId}", time())) {
    $redis->expire("seen:{$msgId}", 86400);
    $redis->rpush('inbox_queue', $payload);
}
http_response_code(200);
echo 'ok';

// Worker (separate process)
while (true) {
    $payload = $redis->blpop('inbox_queue', 5);
    if (!$payload) continue;
    $event = json_decode($payload[1], true);
    try {
        processMessage($event);  // your real logic, may take seconds
    } catch (Throwable $e) {
        logError($e);
        // optional: push to retry queue with backoff
    }
}

With this pattern, the receiver returns 200 in milliseconds regardless of how long your business logic takes. The retry path inside SMS8 then only triggers when your endpoint is actually down or erroring, not because the consumer is slow.

How do I test webhooks during development?

Two clean approaches:

  1. Tunneling. Use cloudflared, ngrok, or tailscale-funnel to expose your dev laptop temporarily. Point the SMS8 webhook at the tunnel URL. Iterate fast.
  2. Replay from production. The SMS8 webhook deliveries log lets you retry any recent delivery by hand. Send a real payload back to your endpoint as many times as needed without sending real SMS.

For unit testing, capture a real signed payload once and check it into a fixtures file. Then your tests verify the signature logic and the handler in isolation. Signature rejection should be exercised by separate fixtures with a tampered body or a wrong secret.

What is the right default in production?

Webhooks first, for everything customer-facing, with a polling safety net. Polling-only integrations make sense for internal back-office tools where the operator is fine with a 60-second lag. Webhooks with proper retry and signature handling rarely fail, and when they do it is usually an expired TLS certificate. Polling jobs fail for boring reasons too (a cron that stopped running, a stale lock file), which is why neither should be your only path.

SMS8 API page with the API key and webhook settings
The API page in SMS8: your key, the send request and the delivery webhooks.

Webhook security checklist

  • Verify signature on every request. Constant-time compare only.
  • Use HTTPS, not HTTP. No exceptions for local testing; use a tunnel like ngrok or cloudflared.
  • Deduplicate on the message ID so a replayed request does nothing.
  • Restrict your endpoint to POST only.
  • Validate payload schema before processing.
  • Rate-limit by IP if you do not trust your TLS termination layer.
  • Log the message ID and a hash of the body, not the body itself. Bodies often contain PII.
  • Rotate the webhook secret every 90 days. Each webhook has its own secret, so add a new webhook, switch your receiver to its secret, then remove the old one.

Latency tracing: where does the time go?

HopWhat affects it
SMS arrives at the gateway phoneThe carrier network delivering to your SIM
Phone forwards to SMS8 backendThe phone's connection (Wi-Fi or mobile data) and battery optimization settings
SMS8 backend dispatches webhook POSTUsually the smallest hop
Network to your endpointWhere your server is hosted, TLS handshake
Your handler processes (queue + 2xx)Whether you queue the work or do it inline

If your handler does heavy work synchronously the 95th percentile climbs fast. The fix is always the same: push the work to a queue, return 200 immediately, do the work async.

Why developers choose SMS8 for incoming SMS

SMS8 gives you signed, retried webhooks out of the box.

  • A developer-friendly API. POST https://app.sms8.io/api/v1/messages with an X-Api-Key header, signed webhooks retried for up to 30 days, and npm install sms8-sdk for the SDK and the sms8 CLI.
  • Your own number. Texts leave from the SIM in your own Android phone, so customers see a number they know and can reply to.
  • A flat price with unlimited messages. USD 29 a month for one phone or Mac, USD 89 for five and USD 229 for twenty, with unlimited SMS and MMS and no per-message fee. Yearly billing is half the price.
  • Made for AI agents. Connect Claude Code with claude mcp add --transport http sms8 https://mcp.sms8.io, or any MCP client through the hosted server or npx -y sms8-sdk mcp.
  • Setup in minutes. Install the app, pair the phone and copy your API key. The 3-day trial includes 30 messages and needs no card.

Start the 3-day trial with 30 messages and no card, or compare plans on the SMS8 pricing page.

Common questions

Still unsure? We answer fast.

Webhook, unless your receiver has no public endpoint.

30 to 60 seconds. Faster is wasteful, slower hurts UX.

Compute sha256= plus the HMAC-SHA256 of the raw body with the webhook signing secret, and constant-time compare it against the X-Signature header.

SMS8 keeps retrying on a growing schedule for up to 30 days, and the message stays available for polling.

Insert the event id into a unique-key table. Treat duplicate-key as "already processed".

Yes, and you should for production. Webhooks primary, slow polling backstop.

Get replies the moment they land

Point an SMS8 webhook at your endpoint and keep a slow poll as the safety net.