Iurii RoguliaIurii Rogulia
AboutAI EngineeringServicesProjectsAI SkillsStackTestimonialsPhrasesBlog
Contact
Iurii ships.

Iurii Rogulia, Senior Agentic AI & Full-Stack Software Engineer. Professionally building software since 2001.

ChecklistsPrivacy PolicyCookie Policy
Just for fun:Think of a numberThink of a birthday

Business

TMI Iurii Rogulia
VAT ID: FI29845875
DUNS: 368664211
Lappeenranta, Finland 🇫🇮

  1. /
  2. Blog
  3. /
  4. Telegram Alerts That Can’t Break Your Stripe Webhook

Iurii Isolates: Telegram Alerts That Can’t Break Your Stripe Webhook

A Telegram outage should cost you one alert, not an order. Here is the split between the critical step and the best-effort one.

November 20, 2026· 10 min read

Best-effort webhook notifications: save the order first, then send Telegram alerts that log failures and never throw. Stripe webhook code and its limits.

Stack

Next.jsTypeScriptNode.js

Services

StripeTelegram

Topics

WebhooksBackend
Telegram Alerts That Can’t Break Your Stripe Webhook

Short answer: in a payment webhook, do the one step you cannot lose first, and let it fail loudly so Stripe redelivers. Only after it has succeeded, send the chat alert, and make that send unable to throw into the handler: catch, log, move on. A Telegram outage then costs you one alert instead of a 500 on a paid order.

The catch is that ‘cannot throw’ is not ‘cannot fail’, and the alert that fails is gone. Below is how I split a Stripe webhook in Pi-Pi, a Next.js and Stripe store whose analytics and order pipeline I built, and then what the design does not protect you from. The snippets are simplified; the structure is what the code does.

What goes wrong when the alert sits in the handler

A payment_intent.succeeded handler usually does a few things: record the order, send some emails, post to a chat. The tempting version awaits all of them in order. Then a slow or failing chat API becomes a payment-path problem. If the alert throws and the handler returns 5xx, Stripe treats the delivery as failed and sends the event again. You have turned a nice-to-have into a retry loop on a payment that already went through.

The opposite mistake is also real: alert first, persist second. Now the warehouse is told about an order that your system failed to save.

So the handler needs two classes of work with different failure rules.

Split the handler: critical step, then best-effort steps

In this handler the order of operations is:

  1. Verify the signature and parse the event.
  2. Look up the order. If its status is already a post-payment one (Paid and later), log a duplicate and stop.
  3. Persist the paid order to the CRM. This write sets the status to Paid, so it is both the sync and the idempotency marker.
  4. Dispatch the notifications, without waiting for them.
  5. Return 200.

Simplified:

const PROCESSED = ["Paid", "Processing", "Shipped", "Delivered"];
 
try {
  const existing = await findOrderByNumber(order.number);
  if (existing && PROCESSED.includes(existing.status)) {
    return NextResponse.json({ received: true }); // duplicate delivery
  }
 
  // Critical: writes status "Paid". Throws on failure.
  await syncPaidOrder(order);
 
  // Best-effort: not awaited, rejections caught.
  void dispatchNotifications(order).catch((err) =>
    log.error({ err, orderNumber: order.number }, "Notification dispatch failed")
  );
} catch (err) {
  log.error({ err }, "Webhook handler failed");
  return NextResponse.json({ error: "Webhook handler failed" }, { status: 500 });
}
 
return NextResponse.json({ received: true });

The critical step is awaited and its failure is not swallowed: the outer catch returns 500 and Stripe redelivers. That is intended: an unsynced paid order is worse than a retry. The dispatch, on the other hand, is void with its own .catch, so nothing it does can reach the outer catch.

A side effect of the ordering: if the critical step fails, no alert has gone out yet. The notifications fire on the redelivery that succeeds, not before.

The dispatch: allSettled plus a catch per task

The notifications go out as one batch, and each task carries its own catch:

async function dispatchNotifications(order: Order): Promise<void> {
  await Promise.allSettled([
    sendWarehouseEmail(order).catch((err) => log.error({ err }, "Warehouse email failed")),
    sendTelegramAlert(order).catch((err) => log.error({ err }, "Telegram alert failed")),
    sendInvoiceEmail(order).catch((err) => log.error({ err }, "Invoice email failed")),
    trackPurchase(order).catch((err) => log.error({ err }, "Purchase tracking failed")),
  ]);
}

Promise.allSettled makes the batch wait for every task without short-circuiting on the first rejection. The per-task .catch gives each failure its own log line saying which step died. Together they mean one broken step does not suppress the others. Running it off the response path also keeps heavier work in the batch, such as rendering an invoice PDF, out of the time Stripe waits for its answer.

The webhook-side question of how to receive events reliably (queues, signature checks, deduplication) is a different problem; I covered it in Stripe webhooks: idempotency, retries and queue setup. That article uses a queue; the handler here writes to the CRM synchronously. This article starts after the critical step is safe.

The sender contract: try/catch, log, never throw

The Telegram module exports a small function per order source. Each one wraps the whole send in try/catch:

export async function sendTelegramAlert(order: Order): Promise<void> {
  try {
    await postToTelegram(buildMessage(order));
  } catch (err) {
    log.error(
      { err, orderNumber: order.number },
      `Telegram notification failed: ${(err as Error).message}`
    );
  }
}

The helper underneath has two rules:

async function postToTelegram(text: string): Promise<void> {
  const token = process.env.TELEGRAM_BOT_TOKEN;
  if (!token) {
    log.warn("TELEGRAM_BOT_TOKEN not set - skipping Telegram notification");
    return;
  }
 
  const res = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ chat_id: CHAT_ID, text }),
  });
 
  if (!res.ok) {
    const detail = await res.text();
    throw new Error(`Telegram sendMessage failed (${res.status}): ${redactSecrets(detail)}`);
  }
}

Here text is whatever your message builder produces. Mine is a compact card for the people packing the order; it contains customer data, so it does not appear here, and a placeholder like New paid order <reference>, <n> items is all you need to follow the code.

  • Unconfigured means skip, not crash. A missing token logs a warning and returns. A development or preview environment without a bot should still process the webhook.
  • A non-2xx response is an error, inside the helper. fetch only rejects on network failure; an HTTP error status is a resolved response. So the helper throws explicitly, and the wrapper above it is what turns that throw into a log line.
  • The response body goes through a redactor. The bot token is part of the request URL, and error text ends up in logs and in an error tracker. I run the body through a secret redactor before it becomes part of the message. That is my reasoning for the redactor, not a guarantee about what Telegram returns.

Note where the try/catch lives: in the exported wrapper, not around the HTTP call everywhere. The helper does throw. The contract is that its callers do not.

An honest point: the swallow is the second layer

Reading this code, you could conclude that the try/catch is what protects the webhook. It is not the only thing. Even without it, a failed alert could not trigger a redelivery here, for two reasons:

  • the dispatch is not awaited, so a rejection never reaches the handler’s outer catch, and its own .catch logs it;
  • if Stripe did send the event again, the status check finds Paid and stops before anything is dispatched twice.

The sender’s try/catch is a second layer. It matters if someone later awaits the dispatch, calls the sender from another place, or removes the outer catch. It also gives a failure one log line with the order reference attached. I would keep it, but I would not claim it is what prevents duplicates. The guard and the fire-and-forget do that.

What this design costs

I would rather you know the limits before copying it.

It needs a long-lived process. Not awaiting the dispatch works because the Node server keeps running after the response is sent. On a platform that freezes or stops the process once the response is returned, un-awaited work is not guaranteed to finish. There you need that platform’s mechanism for work after the response (check its documentation for the exact API), or an outbox. This handler runs on a long-lived server, so the assumption holds here; verify it for yours.

A failed alert is lost. The failure is logged and nothing else happens. There is no retry, no outbox, no dead-letter queue. If Telegram returns an error at that moment, nobody gets that message unless someone reads the log.

There is no timeout. The fetch call in this code sets none. A hanging connection leaves that task pending inside the batch. I have not tested what the runtime’s defaults do in that case, so treat it as an observed gap in this code, not as a measured behaviour. Adding an AbortSignal.timeout(...) is the obvious fix. If you add one, the abort becomes just another error the wrapper logs.

A crash between persist and dispatch loses the alerts. The order is saved and marked Paid, then the process dies before the dispatch runs. On redelivery the guard sees Paid and skips. Nothing re-sends. With the dispatch in memory and no outbox, that window exists.

It is not exactly-once. The duplicate guard is a read of the status followed by a later write. Two deliveries that arrive close together can both read a status that is not yet Paid. It protects against the normal redelivery case, not against true concurrency. If that matters, you need a constraint or a lock on the write, not only a check. For the key-based version of this problem, see idempotency keys for API retries.

The store is part of the design. Here the CRM record is the idempotency marker. That fits this pipeline; I would not present it as the general answer. A database row with a unique constraint is the more common choice.

When this is the wrong design

If the alert is the product, do not do this. A customer-facing notification, a payment receipt someone relies on, an alert that triggers a legal or operational duty: those need delivery tracking. Write the intent to a table in the same step as the critical write (an outbox), have a worker send it, retry with backoff and mark it done. Best-effort is right when a missed message is an inconvenience that someone will notice another way, such as a packing queue that also receives an email.

For work that must be retried and observed, a proper queue is the tool. Background jobs in Node.js covers that side, including a Telegram message when a job finally fails.

Noticing dropped alerts

Best-effort should not mean silent. The failure path above writes an error-level log line with the order reference and the step name. What you do with it depends on your logging stack, but the principle is generic:

  • Treat error-level lines from the notification module as a signal, not noise. If errors from that component are mixed into everything else, nobody will look.
  • Put a log-based monitor on them, with a threshold that fits your volume: one failed alert may be a blip, a run of them means the token or chat changed.
  • Keep the order reference in the line so a missed alert can be re-sent by hand.

In this code the signal is the log line. What watches it is a separate decision.

The webhook is also an inbound surface

Failure isolation is only half of a webhook’s hygiene. Signature verification, replay and secret handling are the other half, and they sit on the inbound side of the same endpoint; webhook security in production covers them. This article is about outbound failure only: what your own side effects are allowed to do to the response.

Checklist

  • Name your one critical step. It is awaited, and its failure returns 5xx.
  • Make that step also your idempotency marker, and check it before you do anything.
  • Dispatch everything else after it, not awaited, with a catch on the outer promise. Only do this on a long-lived process; otherwise use the platform’s after-response mechanism or an outbox.
  • Inside the batch, use Promise.allSettled and a catch per task, each with its own log message.
  • In the sender: try/catch, log with a reference, skip when unconfigured, redact secrets in error text.
  • Set a timeout on the outbound call. This code does not, and you should.
  • Decide, in writing, whether a lost alert is acceptable. If not, use an outbox.
  • Put a monitor on the error log line.

The store this came from is described in the Pi-Pi case study.

Related service

Telegram Bots & Mini Apps

Need order or ops alerts in Telegram that can never block checkout? I wire them in as best-effort side effects, and tell you up front what that costs.

More about this service →

Further reading:

  • Stripe Webhooks: Idempotency, Retries, and Queue Setup – the receiving side
  • Idempotency Keys: Building Retries That Don’t Double-Charge – deduplicating retried requests with a key
  • Webhook Security Beyond the Signature Check – the inbound trust side
  • BullMQ vs pg-boss vs Cron: Node.js Background Jobs Compared – when work must be retried and observed
  • pi-pi.ee – B2B E-commerce for Waterless Urinal Systems – the project
Iurii RoguliaAvailable

Telegram Bots & Mini Apps

Need order or ops alerts in Telegram that can never block checkout? I wire them in as best-effort side effects, and tell you up front what that costs.

More about this service

Relevant client work

View all projects
tsstboxes.com – Fitment-First Online Store for ATV and UTV Cargo Boxes
tsstboxes.com – Fitment-First Online Store for ATV and UTV Cargo Boxes
November 10, 2026
tsstboxes.com – Fitment-First Online Store for ATV and UTV Cargo Boxes

Online store for ATV and UTV cargo boxes, each made for one model. Pick your machine, see only what fits, and pay in USD with shipping included.

pi-pi.ee – B2B E-commerce for Waterless Urinal Systems
pi-pi.ee – B2B E-commerce for Waterless Urinal Systems
January 17, 2026
pi-pi.ee – B2B E-commerce for Waterless Urinal Systems

i18n B2B e-commerce platform for waterless urinal products across 32 European countries with automated VAT handling, PDF invoicing, and CRM integration.

pikkuna.fi – E-commerce for Vinyl Curtains & PVC Products
pikkuna.fi – E-commerce for Vinyl Curtains & PVC Products
October 12, 2024
pikkuna.fi – E-commerce for Vinyl Curtains & PVC Products

E-commerce platform with 30 locales, product configurators, AI chatbot, and fully automated order flow: Stripe → Zoho CRM → Airtable → Mailgun → PDF.

What clients say

“

I’d built most of our MVP with Cursor and it looked finished – it compiled, the tests were green, the demo worked. It just wouldn’t survive real users.

Sebastian Falk 🇸🇪

Founder

Stack

Next.jsTypeScript

Topics

Technical DebtAICode ReviewArchitecture
“

We wanted to add an AI feature that turns messy user notes into structured records, but our first attempt returned unpredictable JSON that broke the app half the time.

Bram de Vries 🇳🇱

Product Lead

Stack

Next.jsTypeScript

Services

OpenAI

Topics

AILLMStructured Outputs
“

We picked vatnode for our B2B billing flow and asked Iurii to help us integrate it properly.

Mārtiņš Liepa 🇱🇻

CTO

Services

Stripe

Topics

Tax/VATB2BAPIWebhooks

Related articles

E-commerce Order Automation: Stripe + Invoice + Shipping Workflow
February 22, 2026· 10 min
E-commerce Order Automation: Stripe + Invoice + Shipping Workflow

E-commerce order automation that cut 160+ hours/month of manual work to zero: Stripe webhook to VAT invoice and tracking in under 2 minutes.

Stack

Next.jsTypeScriptNode.js

Databases

Redis
Stripe Webhooks: Idempotency, Retries, and Queue Setup
January 2, 2026· 11 min
Stripe Webhooks: Idempotency, Retries, and Queue Setup

Stripe webhook production architecture: idempotency keys in PostgreSQL and Redis, a BullMQ queue, and signature verification in Next.js App Router.

Stack

Next.jsTypeScriptNode.js

Databases

PostgreSQLRedis
GA4 Consent Mode Gap: Counting Sales It Hides
November 13, 2026· 8 min
GA4 Consent Mode Gap: Counting Sales It Hides

GA4 consent mode measurement gap: count the paid orders GA4 never saw by replaying its send gate against Stripe PaymentIntent metadata.

Stack

Next.jsTypeScriptNode.js
Wiring an Accounting System into a Payment Webhook Without Losing Money
September 4, 2026· 11 min
Wiring an Accounting System into a Payment Webhook Without Losing Money

How to wire an external accounting or bookkeeping API into a payment flow, and why the call belongs in the queued worker, not the webhook handler.

Stack

TypeScriptNode.js

Databases

PostgreSQL
Subscription Billing: The Edge Cases Stripe Docs Skip
July 22, 2026· 17 min
Subscription Billing: The Edge Cases Stripe Docs Skip

Subscription billing edge cases Stripe glosses over: proration, dunning, the state machine, cancellation timing, refunds, VAT, and webhook ordering.

Stack

Next.jsTypeScriptNode.js

Databases

PostgreSQL