Skip to main content
SiGMA World Rome · booth H7-7129 →
§ Article · Telegram

A fault ends one call: process isolation for Telegram calls

Every Telegram call on DialogBrain runs its native engine in a process of its own. If the engine crashes, that one call is hung up properly, the other person sees "call ended" within a second, and message sync keeps running. This is where the boundary is drawn, what crosses the socket, and how the death of a call process is handled.

Updated 2026-11-29

The guarantee: a fault in a call stays in that call

Telegram calls run on native code: ntgcalls with a WebRTC stack inside, about 135 MB of it, on a few threads that every call of a process shares. Python cannot catch a segfault in such code: the operating system ends the whole process.

We learned what that means while the engine still shared a process with message sync. A null pointer on one audio thread ended the process in the middle of a call. Sync for the Telegram accounts on that instance paused for about ten seconds while they reconnected, and the call could not be hung up properly, because its keys and ids had gone with the process. Messages that arrive during such a pause are caught up (when an account reconnects, the sync engine re-reads the chats where it may have missed something), but a call left hanging in silence is not acceptable.

We guarded that instruction in the library the same day. The lasting answer is a rule that does not depend on any one fix: no native call code runs in the process that syncs messages, and a call engine that dies ends only its own calls, once, with a reason.

Where to cut

There were three places to draw the process boundary. Move everything Telegram for an account into its own process: that is a process for every connected account, running all the time whether or not it ever has a call, and the sync engine’s whole model of an account changes. Move the entire media side (engine, audio bridge, translator): the end state we are heading for, and a larger change than the guarantee needed. Or move only the native engine.

We took the third, because the code already has a boundary there. pytgcalls, the Python library that drives the calls, builds one engine object per account and touches native code only through it: 32 methods and 11 callbacks. Replace that one object with something that forwards each call to another process, and nothing above it has to know.

A call process lives for its account’s calls and 30 seconds after the last one, so their number follows the accounts that have a call in progress. A fresh interpreter with the engine loaded starts in about 0.1 s and holds 26 MB before a call, so there is no pool to keep warm.

# pytgcalls builds one native engine per account and reaches native code
# only through that object. So that object is the place to cut.
call_py = PyTgCalls(client)

engine_class = type(call_py._binding)     # kept for its two static methods
call_py._binding = WorkerBinding(engine_class, account_id)
# The engine object itself is dropped: this process never runs a call.

await call_py.start()   # registers its callbacks on whatever the binding is

What runs where

The sync process keeps everything that must survive a crash: the account’s Telegram session, which carries the signaling (ring, answer, hang up); the owner of each call, which knows its ids; and the bridge to the media room where the agent and the operator are. The child process holds only the engine and the threads it starts.

Telegramservers and the other person’s phonesync processmessages of every channelthe account’s Telegram sessionMTProto clientpytgcallsproxyin the engine’s placecall ownerannounces a call, ends itbridge to the media roommixes agent, operator, fillerno call engine in this processsignaling: ring, answer, hang upcall requests and updatesevery callplay · hang up · framesaudio and video framesaudio both waysmedia roomagent, operatorcall workera process of its ownntgcalls + WebRTCnative threadsworker loopmethods from a table onlyengine callscall audio and videostarts at the first call, ≈0.1 scloses 30 s after the last≈37 MB during an audio callone per accountthat has a call in progressUnix socketcommandsevents, framesping every 5 s

The picture shows why the parent can still act when the child is gone. Hanging up is signaling, and signaling never left the sync process. The child only ever held the media.

What crosses the socket

A Unix socket pair, length-prefixed messages, eight kinds. Control calls, their answers, the engine’s callbacks, and the frames themselves: 100 audio frames a second per call, and raw video when a camera or a screen is on.

The parent never treats the child’s bytes as code. The process on the other end may be one whose memory a native bug has just corrupted, so there is no pickle: each value says what it is, the engine’s 19 structs and 12 enums are named by a number from an append-only table, and a stream that stops being the protocol gets its process killed.

Engine errors cross by class name and are raised on the parent side as the same class. That matters more than it sounds: the library above catches engine errors by class, and so does our own code. A different class for "the same thing, but remote" would have meant an audit of every except clause.

The engine’s threads never wait for the parent. They hand a finished message to the worker’s loop and return. The frame lane is bounded at 24 MB: the oldest video goes first, and audio is dropped only when no video is left to drop, which is logged as a fault because it is heard.

# One message: u32 length | u8 kind | payload, big-endian.
HELLO  = 1   # child  -> parent: versions, pid
CALL   = 2   # parent -> child : id, [method, [args]]
RESULT = 3   # child  -> parent: id, value
ERROR  = 4   # child  -> parent: id, [class name, message]
EVENT  = 5   # child  -> parent: [name, [args]]   (callbacks, frames)
PING   = 6   # parent -> child : id
PONG   = 7   # child  -> parent: id
BYE    = 8   # parent -> child : leave now, nothing is owed

# Values are tagged. A struct or an enum is a NUMBER from an append-only
# table, never a name to import. Every length is checked against what is
# left of the message. Nothing is unpickled or evaluated.

When the worker dies

Nobody outside the process can see it die quickly. In our tests the media room went on showing the dead side as a participant for 21 seconds. Only the parent of the process learns in milliseconds, from the socket closing.

The worker crashesits socket closes within millisecondsThe worker hangstwo missed pings, or 30 s with no answer: killedIts calls are marked lost, at oncerequests still waiting fail as "not in a call"The process is reapedexit status, signal and crash record are keptThe sync process hangs up at Telegramit still holds the account’s session and the call’s ids1:1 call: discardedthe other phone shows "call ended"Group call: leftpeople see the account leaveThe call is filed with its reasonthe next call starts a new worker

The order of the first two boxes is the part that needed the most care. The calls are marked lost synchronously, before the waiting requests fail, so whatever handles such a failure already finds the call marked. Otherwise a retry could ask the engine about a call in the gap and get an answer that means something else.

There is one deliberate exception to "the call is gone". A lost call still answers the question "what kind of call are you" and lets "stop" succeed, until its end has been seen through. That is what lets the library’s ordinary hang-up path run to the end and tell Telegram. Without it the hang-up stops at "not in a call", Telegram is never told, and the other phone shows a live call with nothing in it.

A hang is handled as a crash that has not happened yet. The parent pings the worker’s loop every 5 seconds with 2 seconds to answer, and treats a request unanswered for 30 seconds as a hung engine. Either way the process is killed and the rest is the same path.

We tested it the blunt way: a live call between two of our own accounts, and SIGSEGV sent to the worker in the middle of a sentence. The other side saw the call end 0.6 seconds later. The sync process did not restart, the call was filed as answered and cut short by a fault on our side, and the next call was picked up by a new worker.

def on_socket_closed():
    mark_calls_lost()                 # 1. synchronously, before anyone can ask
    fail_waiting(CallWorkerDied)      # 2. requests in flight learn it
    death = reap_and_read_crash()     # 3. exit status, signal, crash record
    for call in lost_calls:           # 4. the part the other person notices
        hang_up_at_telegram(call)     #    "call ended", not silence
        close_bridge(call)
        file_call_ended(call, reason="call_worker_crashed")

Two calls with one person are two calls

pytgcalls names a call by its chat id. That is fine inside one process and wrong across two, because the call being torn down and the call that person has just started share an id. A teardown that arrives late must not hang up the new call.

So the owner of a call holds a handle to it, and the handle carries a generation. Whatever is said about a call from outside the library (it was lost, it is released) goes through the handle and is checked against the call the worker holds for that chat right now.

The same idea decides who may create a call. A call exists in the worker only when its owner announced it first. A create that nobody announced is refused. The case this closes is a retry that finds its call gone and would otherwise start a new one, which to the person on the other end is their phone ringing again.

No fallback

We rolled it out behind a per-account switch: one account, then every account, with the old path kept as a fallback for a worker that could not start. With every account’s calls running through workers and no worker that failed to start, we deleted the fallback and the switch.

A guarantee with an exception is not a guarantee. As long as the engine could still be loaded "just this once", it could still take the sync process with it. Now a worker that does not say hello within 5 seconds means that one call fails with a stated reason, and the next call starts a worker again. A start problem shows at the first call instead of hiding in a path that nothing exercises.

The test that keeps it true does not check a flag. It builds the real binding, then asserts that the engine object the library created is gone (a weak reference to it is dead) and that the process is back to the number of native threads it had before.

What it costs, and what comes next

Measured in the service’s own image on a development machine: 86 ms from start to the worker’s hello, 0.3 ms for one request and its answer, 37 to 38 MB for a worker during an audio call. An audio call costs about 4.5 % of a core more in total than it did in-process, because the worker runs a Python loop of its own beside the engine.

The next step is already designed: the audio bridge moves next to the engine, and then only control crosses the socket. The protocol, the worker and the death path were built for that from the start.

Or do none of this

This is the kind of work a Telegram call needs before it is dependable, and it is why we offer calls as one request. Connect a Telegram account once; after that the agent dials, greets, holds the conversation, and the transcript lands in the same conversation as your messages with that contact.

curl -X POST https://api.dialogbrain.com/v1/calls \
  -H "X-API-Key: $DIALOGBRAIN_KEY" \
  -H "Idempotency-Key: call-9f21c7" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": 118,
    "target": "telegram:123456789",
    "greeting": "Hi, this is the assistant calling about your order."
  }'
§ Q & A
Can a fault in the call engine interrupt message sync?

No. The call engine runs in a separate process per account, and message sync runs in another. A fault in the engine ends the calls of that one account and nothing else.

Can Python catch a segfault in a native extension?

No. A segfault is delivered to the process, not raised as an exception, and the operating system ends the process. The only reliable containment is a process boundary: run the native code in a child and let the parent survive it.

Why one call process per account and not one for all calls?

With one shared process, a single fault ends every call in progress. With one per account, it ends the calls of that account only. A process is started at the account’s first call and closed 30 seconds after its last, so their number follows the calls in progress, not the number of accounts.

How does the parent learn that the call process died?

From its end of the socket closing, within milliseconds of a crash. For a hang there is a ping every 5 seconds and a 30-second limit on any request; a worker that misses either is killed and handled as a crash.

Why not use pickle between the two processes?

Because unpickling executes what the bytes say, and the other end may be a process whose memory a native bug has just corrupted. The protocol uses tagged values and numbered types from a fixed table, and checks every length.

What does the other person see when the engine crashes mid-call?

Their phone shows the call ended, 0.6 seconds later in our live test. The sync process still holds the account’s session and the call’s ids, so it hangs up properly on the engine’s behalf.

What does process isolation cost per call?

About 0.1 s to start the worker at the first call, 37 to 38 MB of memory during an audio call, and about 4.5 % of a CPU core more than running the engine in-process.