Repeated Telegram updates: avoiding a repeated local action

Tie a receipt and local effect to one MySQL 8.4/InnoDB transaction: a stable key, row locking, replay after commit, and the limits of external delivery.

A repeated event requires checking the local effect that has already been recorded.

A webhook stored a message, the application acknowledged receipt, and a worker began processing it. Then the process stopped. The same job remains in the queue, but did the application action happen? Answering that question solely from the fact of redelivery can either execute the action twice or skip it permanently.

Continue one article_demo on Symfony 8.1 and PHP 8.4+ with the existing inbox from the preceding chapter. A fictional bot adds one mark to a reader counter; the increment itself is not idempotent. WebhookReplay binds a receipt and local change in one MySQL 8.4 schema with InnoDB tables through native PDO MySQL, without adding a second inbox or promising one-time network delivery.

Acceptance and execution have different acknowledgements

The inbox answers, “Did we store the incoming event?” It does not prove that the application action finished. In the setWebhook contract, Telegram describes retries following responses outside 2xx. A retry can also originate inside our application: a worker lost its acknowledgement, a queue returned a job, or an operator started recovery.

The model therefore has two separate records. The first is an immutable accepted event in inbox. The second is a receipt for the local effect in webhook_effect_receipt. That receipt is not for the HTTP response to Telegram: it lets a retrying worker determine whether a specific action has already been applied.

Time can pass between acceptance and execution. User permissions, command eligibility, and current product rules must be checked according to a defined policy before changing application state. This exercise has no real users or commands: the synthetic reader-a is defined in advance as an authorized teaching action. That assumption cannot be transferred to arbitrary Telegram payloads.

The replay key must identify the action

Telegram provides update_id to identify an Update, including handling duplicates and arrival order. The Update documentation also describes a change in the identifier sequence after an extended pause. A filter that discards everything below the last observed number therefore cannot replace tracking individual events.

In shared storage, we form (bot_id, update_id) from the verified server-side bot context and the event identifier. A chat or reader ID does not replace bot_id. The same number from bot-a and bot-b belongs to different streams.

For the effect, we add a stable operation name:

PRIMARY KEY (bot_id, update_id, effect_name)

The exercise uses record-demo-action. The attempt number, a random worker UUID, and the start time do not belong in this key: otherwise, every retry receives a new key. The name should not automatically change with every release either, because that could permit old events to be applied again.

The key does not define all business semantics. Two different Updates with identical text might represent two intentional user commands. If a product must recognize a repeated request across different Updates, it needs a separate request identifier and a rule for executing that request.

The receipt and effect belong in one transaction

Both straightforward orderings are dangerous. Recording “done” before incrementing the counter risks skipping the action after an interruption. Incrementing the counter before recording “done” leaves a window for applying the change twice.

In this model, the worker opens its own outer transaction, locks the already accepted record, and reads the stored event. The receipt has a unique action key. If a receipt already exists and matches this action, the worker does not change the counter. If the receipt is new, the worker inserts it, increments the counter, and commits. Receipt and effect change through one native PDO connection in one InnoDB transaction.

Database uniqueness is what matters for contention: an initial SELECT without a lock does not protect against another executor. Do not carry ON CONFLICT … DO NOTHING into MySQL: MySQL duplicate-key handling has different semantics. Native error 1062 identifies a unique-key conflict, but does not by itself prove that the intended action has already happened: the receipt and its contents must be checked. Other SQL errors are not classified as ordinary duplicates.

A receipt inserted inside an unfinished transaction is not an independently acknowledged success. It becomes evidence of our operation together with the committed effect. On an error before commit, the code rolls back its own active transaction; PDO transaction behavior is described in the PHP documentation.

Before applying the effect, the worker obtains an InnoDB row lock on the accepted event without changing its stored body. This is a row lock, not a reservation of a single writer for the entire database. Receipt and counter change in one transaction; on an SQL error or controlled exception before commit, the code rolls back its own transaction if it is still active and propagates the error to the caller. The after_commit path is outside the rollback block. Actor follows a synthetic reader-* shape; this is not real-reader authorization.

What to check at each interruption point

This model needs more than pressing “run” again. Processing should be interrupted deliberately at different points, followed by reading the persisted state through a separate connection.

Interruption point State expected after rollback or commit Repeated processing
After acceptance, before the worker starts Inbox exists; receipt and effect do not Can execute the action
After inserting the receipt, before the effect Unfinished changes are rolled back Can execute the action
After the effect, before commit Receipt and effect are rolled back together Can execute the action
After commit, before worker acknowledgement Receipt and effect are stored Returns already_applied
During a conflict with another writer Success is not acknowledged Retries with the same key after resolving the cause

In the prepared example, interruption points use local exceptions. The exception after commit is deliberately outside the rollback block: that error handler can no longer undo a completed change. After reopening the database, the worker must check the same key.

This models recovery of control flow; it is not a power-loss or forced-process-termination experiment. Losing a connection around commit can also leave the client with an unknown outcome. Instead of generating a new identifier, the system needs a fresh read or another attempt using the original identity.

One database does not remove contention

InnoDB permits concurrent write transactions, but operations on the same rows can wait for one another. Under REPEATABLE READ, locking does not eliminate lock-wait timeouts 1205 or deadlocks 1213. These errors propagate to the caller; rollback rules are described in the InnoDB error-handling documentation.

The example bounds its lock wait and reports an error to the caller if it cannot write. It has no infinite retry loop and does not report a busy database as successful processing. Scheduling another attempt with a delay, an attempt limit, and separate treatment of permanent failures belongs to the surrounding worker system.

A long HTTP request, image generation, or a wait for an external API must not accidentally enter a short local transaction. Otherwise, one slow step holds a resource needed by other tasks. The prepared handler changes only local tables.

For the teaching contention check, one native connection holds a lock on the relevant row while a second connection to the same schema tries to apply the action. A failed attempt must not be reported as success; after the lock is released, a retry with the same key should produce one committed effect. This scenario does not measure throughput and does not replace multiprocess load testing.

Conflicting replays and the lifetime of memory

An incoming repeat with the same bot/update pair keeps the earlier acceptance contract: the same acknowledgement and the original body without overwrite, even if the repeated payload differs. The worker reads the stored event and checks demo_action and actor_id. Its receipt stores work_sha256 of normalized [bot,id,effect,actor]. If stored work changes after execution, the worker rejects the receipt conflict without a second effect. This is not cryptographic proof of a Telegram request’s origin.

Receipt retention is equally important. Deleting the completion record while retaining the changed counter and allowing an old event again erases the system's memory of that effect. Cleanup must account for every replay source: queues, manual replay, backups, and migrations.

A provider's limited delivery retention period is not the same as the internal replay horizon. A real product needs an explicit archival policy, a minimal retained data set, and a rule for events that are too old. The teaching model does not delete receipts automatically and does not propose keeping every private payload indefinitely.

Why sending to Telegram remains a separate problem

If an external API is called after commit and the process loses the response, the local database does not know whether the external action happened. Calling it inside the transaction does not solve that problem: rollback cannot withdraw a message that has already been sent.

An outbox provides a place to persist delivery intent alongside a local change. It does not, by itself, remove the ambiguity between a successful external call and recording its result. The next step depends on the provider's contract: support for an idempotency key, the ability to retrieve the result, or a separate reconciliation procedure. Such capabilities cannot be assumed merely because a method is named sendMessage.

This example sends no messages and contains no real bots, tokens, or webhook registration. Its local invariant therefore makes no claim about exactly-once Telegram delivery.

Reading and checking the independent example

EffectWorker and ApplyWebhookUpdateCommand run in the same article_demo with the existing MySQL inbox; preserve the earlier routes. HTTP and Console must connect through native PDO MySQL to the same configured MySQL 8.4 schema. Before running them, provision the schema and accounts separately: the migrator performs explicit DDL, while the runtime account has only the required DML privileges, without CREATE, ALTER, or DROP. Initialize the InnoDB tables with FK and CHECK constraints before business transactions; text identities use VARCHAR with utf8mb4_0900_bin, and body uses LONGTEXT. DDL can implicitly commit, so this is neither an atomic schema upgrade nor an automatic transfer of data from the old SQLite file. Constructors and ordinary HTTP/worker calls do not create the schema.

Supply synthetic secrets only through the process environment. The server and worker must use the same dev environment, secret values, and runtime MySQL schema; the separate initialize invocation uses the configured migrator privileges for that schema. The commands below assume those connections are already configured, and the HTTP request expects the local article_demo running at 127.0.0.1:8000 with those values. The MySQL test-fixture wrapper does not automatically configure the HTTP server's connection. No real webhook is registered.

export DEMO_WEBHOOK_SECRET_A='synthetic-secret-a'
export DEMO_WEBHOOK_SECRET_B='synthetic-secret-b'
php bin/console cache:clear --env=dev --no-debug

File config/services.mysql_webhook.yaml:

services:
    webhook_inbox.runtime:
        class: PDO
        arguments:
            $dsn: '%env(DEMO_INBOX_DSN)%'
            $username: '%env(DEMO_INBOX_USER)%'
            $password: '%env(DEMO_INBOX_PASSWORD)%'
            $options:
                !php/const PDO::ATTR_ERRMODE: !php/const PDO::ERRMODE_EXCEPTION
                !php/const PDO::ATTR_DEFAULT_FETCH_MODE: !php/const PDO::FETCH_ASSOC
                !php/const PDO::ATTR_EMULATE_PREPARES: false
    webhook_inbox.migrator:
        class: PDO
        arguments:
            $dsn: '%env(DEMO_INBOX_DSN)%'
            $username: '%env(DEMO_INBOX_MIGRATOR_USER)%'
            $password: '%env(DEMO_INBOX_MIGRATOR_PASSWORD)%'
            $options:
                !php/const PDO::ATTR_ERRMODE: !php/const PDO::ERRMODE_EXCEPTION
                !php/const PDO::ATTR_DEFAULT_FETCH_MODE: !php/const PDO::FETCH_ASSOC
                !php/const PDO::ATTR_EMULATE_PREPARES: false
    App\WebhookDemo\MysqlInbox:
        autowire: true

File src/Command/InitializeWebhookInboxCommand.php:

<?php

declare(strict_types=1);

namespace App\Command;

use App\WebhookDemo\MysqlInbox;
use App\WebhookReplay\EffectWorker;
use PDO;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

#[AsCommand(name: 'app:webhook-demo:initialize', description: 'Initialize the synthetic local inbox.')]
final class InitializeWebhookInboxCommand extends Command
{
    public function __construct(
        #[Autowire(service: 'webhook_inbox.migrator')]
        private readonly PDO $migrator,
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        MysqlInbox::initialize($this->migrator);
        EffectWorker::initialize($this->migrator);
        $output->writeln('Synthetic inbox initialized.');
        return Command::SUCCESS;
    }
}

For a local run, create a separate empty schema and two distinct accounts as a MySQL administrator. Replace the placeholders with your own values. Runtime has DML only; supply the migrator only to a separate initialization process. Save runtime variables in untracked .env.local. This example does not transfer data from old SQLite files.

CREATE DATABASE demo_inbox CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;
CREATE USER 'demo_inbox_r'@'127.0.0.1' IDENTIFIED BY '<runtime-password>';
CREATE USER 'demo_inbox_m'@'127.0.0.1' IDENTIFIED BY '<migrator-password>';
GRANT SELECT, INSERT, UPDATE, DELETE ON demo_inbox.* TO 'demo_inbox_r'@'127.0.0.1';
GRANT CREATE, ALTER, INDEX, REFERENCES, SELECT, INSERT, UPDATE, DELETE, TRIGGER ON demo_inbox.* TO 'demo_inbox_m'@'127.0.0.1';
DEMO_INBOX_DSN="mysql:host=127.0.0.1;port=3306;dbname=demo_inbox;charset=utf8mb4"
DEMO_INBOX_USER=demo_inbox_r
DEMO_INBOX_PASSWORD="<runtime-password>"
read -r -p 'Migrator user: ' DEMO_INBOX_MIGRATOR_USER
read -r -s -p 'Migrator password: ' DEMO_INBOX_MIGRATOR_PASSWORD
printf '
'
export DEMO_INBOX_MIGRATOR_USER DEMO_INBOX_MIGRATOR_PASSWORD
php bin/console app:webhook-demo:initialize
unset DEMO_INBOX_MIGRATOR_USER DEMO_INBOX_MIGRATOR_PASSWORD

801 is a teaching Update ID without an already applied effect in this inbox. If it has been used, choose another for a new synthetic event; retain the same ID and body during retries. Preserve the existing database when repeating the exercise.

curl -i -X POST http://127.0.0.1:8000/webhook-demo/demo-route-a \
  -H 'Content-Type: application/json' \
  -H 'X-Telegram-Bot-Api-Secret-Token: synthetic-secret-a' \
  --data '{"update_id":801,"demo_action":"record-demo-action","actor_id":"reader-a"}'
php bin/console demo:webhook:apply bot-a 801 --env=dev --no-debug
php bin/console demo:webhook:apply bot-a 801 --env=dev --no-debug

The verification contract covers replay, rollback after receipt insertion and after the effect, retry after commit, bot isolation, changed stored-work conflicts, invalid actors, contention, and passing an accepted HTTP event to separate Console processes. For a new permitted event, expect applied and then already_applied with one counter increment. MySQL tests use the shared guarded disposable-fixture mechanism App\Infrastructure\MysqlLab and actual separate native connections to one schema; the migrator performs DDL during setup, while assertions and runtime code perform DML. Controlled exceptions and separate connections establish neither SIGKILL/power-loss recovery nor multiprocess throughput.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/WebhookReplay
  1. Distribution Publishing to a channel: draft, approval, delivery and reconciliation
  2. Distribution A stale callback: menu versions and authorization when the action runs
  3. Distribution One webhook for several bots: choosing the right context
  4. Databases Handler idempotency: repeat the task without duplicating its result