One webhook for several bots: choosing the right context
A shared receiver for two bots: a server route registry, secret verification, isolated contexts, and MySQL inbox storage before HTTP acknowledgement.
Two bots send superficially similar messages to the same application. Both contain an update_id, a user, and a chat. Yet one bot’s command must not enter the other bot’s queue or use its token. The most dangerous mistake happens before the command runs: the receiver allows the incoming JSON to choose whose authority it will use.
The WebhookDemo module adds POST /webhook-demo/{routeKey} to the same application. It uses a separate MySQL 8.4/InnoDB inbox through native PDO and synthetic secrets only. The exercise registers no Telegram webhook, sends no messages and executes no bot commands.
Consider a shared receiver for two fictional bots. Here, “one webhook” means one handler in the application. Each bot is configured with its own URL for the same route: /webhook-demo/demo-route-a and /webhook-demo/demo-route-b. Sharing the processing code does not turn every request into one trusted stream.
Three values that are easy to confuse
The route needs a key, the stored event needs an internal bot identity, and future sending needs a reference to outbound credentials. These values have different responsibilities.
| Value | Its purpose | What it does not prove |
|---|---|---|
Route key demo-route-a |
Find a candidate in the server registry | That a trusted sender made the request |
Internal ID bot-a |
Associate the event with its context | That the user may execute any command |
Reference demo-credential-a |
Select credentials in a separate sending adapter | That incoming JSON may choose a token |
These are synthetic values for a local exercise. A route key is not a bot token. Knowing the URL alone does not grant admission to processing, and a chat identifier does not replace the bot’s identity.
The server registry maps a route key to a context. An unknown key is rejected. It does not automatically create a bot, become an environment variable name, or select an arbitrary credentials file.
Find a candidate, then check the secret
Telegram delivers an Update through HTTPS POST. The setWebhook parameter secret_token supplies X-Telegram-Bot-Api-Secret-Token; a response outside 2xx triggers a limited series of retries. The setWebhook contract describes this behavior.
In our receiver, each route has its own expected secret. Once it finds a candidate, the code compares that value with the request header. The comparison uses hash_equals, with the server’s known value first and the received value second. The event cannot reach the inbox before this check completes.
The secret header is not a signature over the JSON body, and it does not eliminate repeat delivery. Someone who obtains the secret can submit it with a different body. It therefore belongs in neither a URL nor error messages or ordinary access logs. Transport protection, secret storage, and permission for a particular application action remain separate concerns.
A missing, empty, or incorrect header is rejected. The example also rejects multiple values when Symfony exposes them. However, the application receives headers after the web server and proxy have processed them: the number of values in HeaderBag does not establish how many lines appeared in the original request. Duplicate-header behavior at the actual ingress needs its own check.
Message fields do not change the context
After verification, the server passes its internal bot-a to storage. Adding bot_id: "bot-b" to the JSON does not change that choice. A credential_reference field cannot reassign the future sender either.
This matters even for a request that passed the header check. Input can contain extra fields, new event types, or a deliberately crafted command. Trust in the delivery mechanism does not imply trust in every decision suggested by the body.
In this example, the verified context exists only on the server. The inbox stores the internal bot ID alongside the event. If a worker is introduced later, it should restore an allowed context from that ID. There is no need to serialize the complete object, including the header secret, into the queue. Only the sending component should obtain the outbound token; this exercise contains no such component.
User and chat permissions still require a separate check. For example, admitting a message for bot A does not authorize its author to publish an article. That is a rule for the particular command, evaluated after the bot has been identified.
The envelope accepted by the teaching route
The route in the single article_demo accepts POST only. WebhookDemoController reads headers and content through HttpFoundation. JSON must be an object with an integer, nonnegative update_id.
We also choose a limit of 65,536 bytes and Content-Type: application/json. This is the local example’s policy, not a stated Telegram limit. Checking length after reading the body does not prevent buffering it: a real environment needs a corresponding limit ahead of the application.
Checking the envelope is not full validation of every Update variant either. The receiver does not execute commands or attempt to understand every field immediately. It stores an admitted event for the next stage. The practical boundary follows from that choice: a valid update_id is needed to account for delivery, but it does not authorize an arbitrary command.
Accepting an event means storing it before replying
In an asynchronous flow, an acceptance response should be backed by a stored event. Returning 200 and then attempting to save creates a loss window: the process can stop between those actions.
The example controller calls Inbox::accept(). For a new event, the MysqlInbox implementation explicitly commits the inserted row before returning true. If MySQL returns duplicate error code 1062, the implementation rolls back the attempted insertion and returns false without committing: this branch acknowledges the already stored event without replacing its body. Other write or commit failures propagate to the controller, which returns 503; an unfinished transaction owned by the operation is rolled back. These storage errors do not become successful acknowledgements. Transaction error handling is described in the InnoDB documentation.
Here, 200 means only that the inbox accepted the event. It does not mean the command has executed or a message has been sent. A worker, an outbound work queue, and failure recovery are further parts of the system; naming a method accept does not implement them automatically.
The tests read the saved inbox through separate native PDO connections sharing the same MySQL schema and check a Kernel reboot. This checks visibility of committed data and recognition of a duplicate, but it does not simulate power loss or disk failure. The reliability of a particular storage device and process behavior after crashes require separate experiments.
Count duplicates within one bot
An Update has an identifier useful for duplicate and out-of-order delivery handling. In the shared inbox, we choose (bot_id, update_id) so that the uniqueness scope belongs to a particular bot.
File src/WebhookDemo/MysqlInbox.php:
<?php
declare(strict_types=1);
namespace App\WebhookDemo;
use PDO;
use PDOException;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
final class MysqlInbox implements Inbox
{
public function __construct(
#[Autowire(service: 'webhook_inbox.runtime')]
private readonly PDO $db,
) {
}
/** Explicit migration only: call with a DDL-capable connection before business transactions. */
public static function initialize(PDO $migrator): void
{
if ($migrator->inTransaction()) {
throw new \LogicException('Inbox migration cannot run inside a transaction.');
}
$migrator->exec('CREATE TABLE IF NOT EXISTS inbox (
bot_id VARCHAR(256) NOT NULL,
update_id BIGINT NOT NULL,
body LONGTEXT NOT NULL,
PRIMARY KEY (bot_id, update_id),
CONSTRAINT inbox_nonnegative_update CHECK (update_id >= 0)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin');
}
public function accept(string $botId, int $updateId, string $body): bool
{
// A byte bound is deliberately stricter than VARCHAR's character bound.
// Validate before starting a transaction, including on duplicate deliveries.
if (strlen($botId) > 256 || preg_match('//u', $botId) !== 1) {
throw new \InvalidArgumentException('Bot identity must be valid UTF-8 of at most 256 bytes.');
}
if ($updateId < 0) {
throw new \InvalidArgumentException('Update identity must be nonnegative.');
}
if ($this->db->inTransaction()) {
throw new \LogicException('The inbox must own its outer transaction.');
}
$this->db->beginTransaction();
try {
$statement = $this->db->prepare('INSERT INTO inbox (bot_id, update_id, body) VALUES (?, ?, ?)');
try {
$statement->execute([$botId, $updateId, $body]);
} catch (PDOException $error) {
// Only the primary-key duplicate is an accepted replay. Do not
// suppress CHECK, encoding, permission, deadlock or timeout failures.
if (($error->errorInfo[1] ?? null) !== 1062) {
throw $error;
}
$this->db->rollBack();
return false;
}
$this->db->commit();
return true;
} catch (\Throwable $error) {
if ($this->db->inTransaction()) {
$this->db->rollBack();
}
throw $error;
}
}
}
The events bot-a / 7 and bot-b / 7 create two rows. Repeating bot-a / 7 does not create a third or overwrite the original body. In MySQL, the composite primary key (bot_id, update_id) enforces the final rule; the MySQL documentation describes uniqueness conflicts and their handling. Asking whether a row exists and then inserting it separately is insufficient for concurrent admission: the final uniqueness rule belongs in storage.
The receiver does not discard an event merely because its identifier is smaller than the last one seen. The exercise does not establish command execution order at all. Deduplication and ordering are different rules; one should not be hidden inside the other.
Removing an incoming duplicate does not guarantee a single external effect either. A worker can send a message and stop before recording the result. Repeating its work then requires separate idempotency or reconciliation of an ambiguous outcome. Even an outbox alone is no basis for promising exactly-once behavior for an external API.
A matrix that exposes mixed bot contexts
| Scenario | Example policy | What to check in the inbox |
|---|---|---|
| Unknown route | 404 | No new rows |
| Route A with secret B | 403 | No new rows |
A with its correct secret, but bot_id B in the body |
200 | The row belongs to A |
Same update_id for A and B |
200 for both | Two separate rows |
| Repeated key for A | Same 200 response | No second A row |
| Invalid JSON envelope | 400 | No new rows |
| Body above the chosen limit | 413 | No new rows |
| Unsupported Content-Type | 415 | No new rows |
| Unavailable storage | 503 | Successful acceptance is not claimed |
For a real receiver, add concurrent requests, process restarts, proxy rules, and payload retention to this matrix. A successful local test, once run, will not replace those checks either.
The bot context must be established before the application action and travel with it into subsequent stages. A shared handler can then reuse the admission mechanics while each bot’s authority remains attached to its verified context.
Add the module to the same application
Add src/WebhookDemo, src/Controller/WebhookDemoController.php and src/Command/InitializeWebhookInboxCommand.php. Within the same application, the inbox has separately configured MySQL connections named webhook_inbox.runtime and webhook_inbox.migrator. Before the first POST, provision the schema and accounts and run APP_ENV=dev php bin/console app:webhook-demo:initialize with the migrator configured. The command explicitly creates the schema before event handling; HTTP code uses a DML account without CREATE, ALTER or DROP privileges. MySQL DDL can cause implicit commits, so this is neither an atomic schema upgrade nor an automatic data migration from an old SQLite file.
In config/services.yaml, preserve earlier registrations, imports and _defaults. The module’s MySQL connections are loaded through the services.mysql_webhook.yaml import, and Inbox aliases MysqlInbox. Do not replace the application’s entire configuration with only the webhook module’s definitions.
services:
_defaults: { autowire: true, autoconfigure: true }
App\WebhookDemo\BotRegistry:
arguments:
$botASecret: '%env(DEMO_WEBHOOK_SECRET_A)%'
$botBSecret: '%env(DEMO_WEBHOOK_SECRET_B)%'
App\WebhookDemo\Inbox:
alias: App\WebhookDemo\MysqlInbox
App\Controller\WebhookDemoController: ~
App\Command\InitializeWebhookInboxCommand: ~
webhook_replay.connection:
alias: webhook_inbox.runtime
App\WebhookReplay\EffectWorker:
arguments:
$db: '@webhook_replay.connection'
App\Command\ApplyWebhookUpdateCommand: ~
Merge these definitions into the existing services block in config/services_test.yaml, preserving earlier test settings:
services:
App\WebhookDemo\Inbox:
alias: App\WebhookDemo\MysqlInbox
public: true
bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/WebhookDemo
The bot secrets in the tests are synthetic strings only. Tests run through the shared guarded disposable MySQL fixture: App\Infrastructure\MysqlLab prepares an isolated schema through a separate migrator, while assertions and runtime code perform DML only. The test wrapper does not automatically configure a separate dev HTTP process: the local route needs its own schema and account configuration. MySQL connections use the network, but there are no Telegram calls. The Kernel reboot check reads the committed inbox and recognizes a repeated update.
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.
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
Check the current example against an owned disposable MySQL schema: