Developer docs
16. Multi-DC model
On this page
Telvoro is deployed as one DC today, but the protocol, the IDs and the SDK are ready for
several data centres, following Telegram’s model: every account is homed to one DC,
the client talks to its home DC, files live where they were uploaded, and a DC that
cannot serve a request answers DC_MIGRATE with the DC that can. Cross-DC routing between
servers is not implemented yet (see “Deferred”).
16.1 DC id and the DC list
- A DC id is an integer in
1..255(one byte insidefile_ids). A server’s own id isServerConfig.this_dc(TELEVO_DC_ID, default 1). A server that leaves it 0 is a pre-multi-DC server: treat it as DC 1. ServerConfig.dcslists every DC the client may be sent to, the current one included:DcOption{id, ws_url, quic_addr, http_url, file_base_url, media_only, cdn}.ws_urlis thewss://…/v1/wsendpoint,quic_addrthehost:portof the QUIC listener (empty = no QUIC),http_urlthe Connect base URL,file_base_urlthe base of signed download URLs (same meaning as the oldServerConfig.file_base_url, which is kept and still filled).media_only: the DC servesFilesServicedownloads only; never make it a home DC.cdn: an untrusted cache for public media; reserved, no server sets it yet.- The same id may appear more than once (e.g. one
media_onlyentry). Prefer amedia_onlyentry for downloads and a non-media_onlyone for everything else.
- Clients keep the latest list (it comes with every
welcome) as their DC map. Never replace the URL you are connected with by the advertised URL of the same DC: the advertised URL is the public one, while the client may legitimately use another route (an emulator’s10.0.2.2, a proxy). The map is only used to reach a different DC.
16.2 What lives where
| Object | Lives on | Rule |
|---|---|---|
user (account, sessions, contacts, settings, user log seq) | the user’s home DC | chosen at sign-up and never changes on its own; the DC is encoded in the user id |
private chat, group, channel (messages, chat log pts, members) | the DC of the chat id | the creator’s home DC at creation time |
| file | the DC that minted the file_id | the uploader’s home DC; the DC is in the file_id |
| session | the DC that minted the token | a token is only valid there |
| bots | the bot’s home DC | the bot id (prefix of the bot token) names it; the Bot API front end is central (§16.7) |
well-known accounts (777000) | every DC | ids below 1 000 000 are reserved and exist on every DC |
16.3 Globally unique IDs
User, chat, session, file, sticker-set, sticker (= custom-emoji id), call and secret-chat ids are unique across all DCs. Every DC draws them from its own decimal range of the same Postgres sequences:
SPAN = 10^12
DC 1: [1, 2·SPAN) (all ids minted before multi-DC are here)
DC d (d ≥ 2): [d·SPAN, (d+1)·SPAN)
dc_of(id) = max(1, floor(id / SPAN))
So DC 2’s first user is 2 000 000 000 000; a DC has 10^12 ids per kind. The largest id
any DC can mint is 256·10^12 − 1 ≈ 2^47.9.
Why this scheme:
- JS/JSON safety. Browsers and Dart on the web hold
int64s as doubles once an app calls.toInt()(the app does, for ids), and the Bot API sends ids as JSON numbers. Everything must stay below 2^53. The worst case is the Bot API’s channel id-(10^12 + chat_id)=-(257·10^12 − 1), still about 35× below 2^53. Telegram’s own guarantee for Bot API ids is 52 bits; ours are 48. - Bot API compatibility. User ids stay positive. Group and channel ids keep the
existing
-(10^12 + id)mapping (BOT_API.md), so every chat id minted so far keeps its Bot API id, and the mapping stays a bijection for every DC. - Existing data stays valid. DC 1’s range contains every id minted so far, so DC 1’s migration only adds an upper bound to its sequences; nothing is renumbered.
- No clocks, no new columns. Ids still come from a Postgres sequence in the same
transaction, stay dense and ordered per DC, and every foreign key stays one
bigint. A composite(dc, id)key would touch every table and could not be a Bot API number. - Rejected: snowflake ids. A 64-bit snowflake (41-bit ms time | dc | sequence) is not JS-safe. A 53-bit one leaves about 12 bits per millisecond for sequence plus DC, ties correctness to wall clocks, and leaks creation times. A single DC has no throughput problem that a sequence cannot handle.
- Human readable.
dc_ofis the leading digits of the id.
A DC records its id in the database the first time it starts and refuses to start with a
different TELEVO_DC_ID afterwards, and its sequences are bounded by MAXVALUE, so it
fails loudly instead of minting ids in a neighbour’s range.
Message ids stay per chat ((chat_id, id)), pts/seq stay per chat / per user, and
queue/audit ids (push log, media jobs, reports…) never leave their DC. None of them needs
a DC range.
Clients MUST still treat ids as opaque int64s. dc_of is for servers, for debugging and
for the routing hints below.
16.4 file_id format
file_ids stay opaque capabilities, but the DC is now readable as a routing hint:
v1 (old, still accepted): "F" + base64url( id(8) | mac(16) ) → DC 1
v2: "F" + base64url( 0x02 | dc(1) | id(8) | mac(16) )
mac = HMAC-SHA256(file key, "file2" ‖ 0x02 ‖ dc ‖ id)[:16]
A v1 id decodes to 24 bytes and a v2 id to 26 bytes. A client MAY read the DC byte of a
v2 id (a v1 id is DC 1) to open the right connection before it calls GetFile. The
server stays authoritative: a download on the wrong DC returns DC_MIGRATE. unique_id
is unchanged.
16.5 DC_MIGRATE
Error{code: 303, type: "DC_MIGRATE", dc_id, migrate_scope} means “repeat this request
on DC dc_id”. migrate_scope says what moves:
| scope | When | Client does |
|---|---|---|
MIGRATE_SCOPE_HOME | SendCode/SignIn for a phone or email homed elsewhere (Telegram’s PHONE_MIGRATE); a token or bot token minted by another DC, in welcome.error or on HTTP (USER_MIGRATE) | switch the main connection to that DC (keep the token), then repeat the request. This DC is now home. |
MIGRATE_SCOPE_REQUEST | FilesService/GetFile / GetFileUrl for a file stored elsewhere (FILE_MIGRATE) | repeat only this request on a connection to that DC (§16.6); home does not change |
Rules:
dc_idis always inServerConfig.dcs. A client that does not know the DC fails the request. It MUST NOT guess a URL.- Follow at most 3 migrations per request. A loop is a server bug.
welcome.error = DC_MIGRATEleaves the connection unauthenticated. Reconnect to the target DC with the same token. Do NOT drop the token as for401.- On HTTP (Connect) the error is a Connect error with code
failed_preconditionand atelevo.v1.Errordetail. retry_afteris unused. Themessagenames the cause (PHONE,USER,FILE) for logs only.
Session tokens minted from now on carry the minting DC, "<dc>." + base64url(32 random bytes), so a DC can answer a foreign token with DC_MIGRATE instead of
SESSION_REVOKED. Tokens without a dot are DC 1 tokens. Tokens are still opaque to
clients.
16.6 Moving the authorization: ExportAuthorization / ImportAuthorization
A client that needs a second DC (a file on another DC; later, a media-only DC) does not log in again:
home: AuthService/ExportAuthorization{dc_id} -> {id: user_id, bytes}
target: AuthService/ImportAuthorization{id, bytes} -> AuthResult{user, token, session_id}
bytesis a signed, opaque grant (≈115 bytes): version, source DC, destination DC, user id, exporting session, issue and expiry times, a 128-bit random nonce, and an Ed25519 signature by the source DC’s auth-transfer key.- The grant expires 60 s after export and is single-use. The destination DC records the nonce and rejects a second import.
- The destination DC accepts a grant only if the signature verifies under the source DC’s
key,
dst == this_dc,idequals the user in the grant, and the user’s id belongs to the source DC (only a user’s home DC can vouch for it). - Errors:
400 DC_ID_INVALID(export to a DC not in the DC list),400 AUTH_BYTES_EXPIRED,400 AUTH_BYTES_INVALID(anything else: bad signature, wrong DC, wrong user, already used). - The imported session belongs to the exporting session. It does not appear in
GetSessions, it is not announced to the user as a new login, and it is revoked when the exporting session is revoked. - Exporting to your own DC is allowed (that is the single-DC case and how the server tests it). A client normally exports only to a DC other than home.
ImportAuthorizationis public (no session needed), likeSignIn. On a WebSocket or QUIC connection it authenticates the connection.
SDK behaviour: file connections to a foreign DC are opened on demand (no updates). They
are authorized with export/import once per DC per process, re-authorized after a 401,
and closed when idle.
16.7 Bot API: one front end, DCs invisible
Bot developers never see DCs. Every DC serves the whole Telegram-compatible Bot API
(/bot<token>/<method> and /file/bot<token>/<path>). Operators can therefore put one
public hostname (e.g. api.televo.example) in front of any DC, or all of them, and
unmodified Telegram bot libraries keep working.
- Routing. The bot token
<bot_id>:<secret>names the bot’s home DC throughdc_of(bot_id). A DC that is not the bot’s home reverse-proxies the request to the home DC’sDcOption.http_url(an origin, no path). It streams the request and response unchanged: JSON and form bodies, multipart uploads, long-pollgetUpdatesand file downloads. The home DC does all the work (token check, rate limits, updates). - DC-to-DC authentication. The proxied request carries
X-Televo-Dc-Auth: v1.<src>.<dst>.<unix_ms>.<sig>.sigis the source DC’s Ed25519 auth-transfer key (§16.6) over"televo-dc-rpc-v1\n<src>\n<dst>\n<unix_ms>\n<METHOD>\n<request URI>". It is valid for ±60 s,dstmust be the receiving DC, andsrcmust be a known DC with a configured key other than the receiver itself. A request that carries the header is served only if the header verifies (anything else:403), and it is never proxied again, so there are no loops. Bodies are not signed: the hop is TLS. - A token whose DC is unknown is an ordinary invalid token (
401). - Webhooks are always sent by the bot’s home DC.
- Speaking the protocol directly (not the Bot API),
ImportBotAuthorizationon the wrong DC returnsDC_MIGRATE(HOME). - Messages to a user on another DC.
sendMessage(chat_id = user id)wheredc_of(user_id)is another DC calls the DC-to-DC deliver-to-user RPC (§16.8). BOT_CANT_INITIATE semantics are unchanged: the recipient’s DC delivers only if the user started the bot or sent it a join request. Until cross-DC delivery exists, that case (and only that case) is400 Bad Request: cross-DC delivery is not available yet. A single-DC deployment never hits it.
16.8 Deferred
- Server-to-server routing. Chats with members on several DCs, cross-DC private chats, forwarding a file from another DC, global username/phone directories and cross-DC search. Today every object lives on the single DC.
- Placement. New accounts are homed by phone prefix (
TELEVO_DC_PLACEMENT, e.g.+44=2). With one DC the table is empty and everyone is homed here. A real deployment needs a global phone→DC directory so that an existing account found on another DC is migrated too. - Changing a user’s home DC (moving the account’s data).
- Cross-DC session management.
GetSessions/TerminateSessiononly see the current DC. Revoking a home session does not yet revoke the sessions it imported on other DCs; the 60 s / single-use grant limits that window to sessions already imported. - CDN DCs (
cdnflag): encrypted public media served by untrusted caches. - Cross-DC delivery (deliver-to-user). Interface defined (
service.DCPeer):POST {http_url}/internal/dc/v1/deliver_to_userwith the §16.7 DC header,{sender_id, recipient_id, request: SendMessageRequest}→ the storedMessageas the sender sees it, or anError. The recipient’s DC owns the private chat and enforces BOT_CANT_INITIATE, blocks and privacy. Still to build:- the receiving handler;
- a sender-side mirror of the private chat (dialog,
pts, updates for the sender’s other devices and for the bot’sgetUpdates); - replies flowing back the other way;
- media from the sender’s DC;
- user stubs (name/photo) of remote users;
- the same path for users, not just bots. Other Bot API methods with a remote user’s chat id return the same 400 until then.
Generated from docs/PROTOCOL.md in the Telvoro repository. Wire names such as televo.v1 are unchanged.