<buttonid="sidebar-toggle"class="icon-button"type="button"title="Toggle Table of Contents"aria-label="Toggle Table of Contents"aria-controls="sidebar">
<ahref="https://github.com/matrix-org/synapse/edit/develop/docs/development/synapse_architecture/streams.md"title="Suggest an edit"aria-label="Suggest an edit">
<iid="git-edit-button"class="fa fa-edit"></i>
</a>
</div>
</div>
<divid="search-wrapper"class="hidden">
<formid="searchbar-outer"class="searchbar-outer">
<inputtype="search"id="searchbar"name="searchbar"placeholder="Search this book ..."aria-controls="searchresults-outer"aria-describedby="searchresults-header">
<p>Synapse has a concept of "streams", which are roughly described in <ahref="https://github.com/matrix-org/synapse/blob/develop/synapse/storage/util/id_generators.py"><code>id_generators.py</code></a>.
Generally speaking, streams are a series of notifications that something in Synapse's database has changed that the application might need to respond to.
For example:</p>
<ul>
<li>The events stream reports new events (PDUs) that Synapse creates, or that Synapse accepts from another homeserver.</li>
<li>The account data stream reports changes to users' <ahref="https://spec.matrix.org/v1.7/client-server-api/#client-config">account data</a>.</li>
<li>The to-device stream reports when a device has a new <ahref="https://spec.matrix.org/v1.7/client-server-api/#send-to-device-messaging">to-device message</a>.</li>
</ul>
<p>See <ahref="https://github.com/matrix-org/synapse/blob/develop/synapse/replication/tcp/streams/__init__.py"><code>synapse.replication.tcp.streams</code></a> for the full list of streams.</p>
<p>It is very helpful to understand the streams mechanism when working on any part of Synapse that needs to respond to changes—especially if those changes are made by different workers.
To that end, let's describe streams formally, paraphrasing from the docstring of <ahref="https://github.com/matrix-org/synapse/blob/a719b703d9bd0dade2565ddcad0e2f3a7a9d4c37/synapse/storage/util/id_generators.py#L96"><code>AbstractStreamIdGenerator</code></a>.</p>
<p>A stream is an append-only log <code>T1, T2, ..., Tn, ...</code> of facts<supclass="footnote-reference"><ahref="#1">1</a></sup> which grows over time.
Only "writers" can add facts to a stream, and there may be multiple writers.</p>
<p>Each fact has an ID, called its "stream ID".
Readers should only process facts in ascending stream ID order.</p>
<p>Roughly speaking, each stream is backed by a database table.
It should have a <code>stream_id</code> (or similar) bigint column holding stream IDs, plus additional columns as necessary to describe the fact.
Typically, a fact is expressed with a single row in its backing table.<supclass="footnote-reference"><ahref="#2">2</a></sup>
Within a stream, no two facts may have the same stream_id.</p>
<blockquote>
<p><em>Aside</em>. Some additional notes on streams' backing tables.</p>
<ol>
<li>Rich would like to <ahref="https://github.com/matrix-org/synapse/issues/13456">ditch the backing tables</a>.</li>
<li>The backing tables may have other uses.
> For example, the events table serves backs the events stream, and is read when processing new events.
> But old rows are read from the table all the time, whenever Synapse needs to lookup some facts about an event.</li>
<li>Rich suspects that sometimes the stream is backed by multiple tables, so the stream proper is the union of those tables.</li>
</ol>
</blockquote>
<p>Stream writers can "reserve" a stream ID, and then later mark it as having being completed.
Stream writers need to track the completion of each stream fact.
In the happy case, completion means a fact has been written to the stream table.
But unhappy cases (e.g. transaction rollback due to an error) also count as completion.
Once completed, the rows written with that stream ID are fixed, and no new rows
<p>For any given stream reader (including writers themselves), we may define a per-writer current stream ID:</p>
<blockquote>
<p>The current stream ID <em>for a writer W</em> is the largest stream ID such that
all transactions added by W with equal or smaller ID have completed.</p>
</blockquote>
<p>Similarly, there is a "linear" notion of current stream ID:</p>
<blockquote>
<p>The "linear" current stream ID is the largest stream ID such that
all facts (added by any writer) with equal or smaller ID have completed.</p>
</blockquote>
<p>Because different stream readers A and B learn about new facts at different times, A and B may disagree about current stream IDs.
Put differently: we should think of stream readers as being independent of each other, proceeding through a stream of facts at different rates.</p>
<p><strong>NB.</strong> For both senses of "current", that if a writer opens a transaction that never completes, the current stream ID will never advance beyond that writer's last written stream ID.</p>
<p>For single-writer streams, the per-writer current ID and the linear current ID are the same.
Both senses of current ID are monotonic, but they may "skip" or jump over IDs because facts complete out of order.</p>
<p><em>Example</em>.
Consider a single-writer stream which is initially at ID 1.</p>
<p>There are two ways to view a multi-writer stream.</p>
<ol>
<li>Treat it as a collection of distinct single-writer streams, one
for each writer.</li>
<li>Treat it as a single stream.</li>
</ol>
<p>The single stream (option 2) is conceptually simpler, and easier to represent (a single stream id).
However, it requires each reader to know about the entire set of writers, to ensures that readers don't erroneously advance their current stream position too early and miss a fact from an unknown writer.
In contrast, multiple parallel streams (option 1) are more complex, requiring more state to represent (map from writer to stream id).
The payoff for doing so is that readers can "peek" ahead to facts that completed on one writer no matter the state of the others, reducing latency.</p>
<p>Note that a multi-writer stream can be viewed in both ways.
For example, the events stream is treated as multiple single-writer streams (option 1) by the sync handler, so that events are sent to clients as soon as possible.
But the background process that works through events treats them as a single linear stream.</p>
<p>Another useful example is the cache invalidation stream.
The facts this stream holds are instructions to "you should now invalidate these cache entries".
We only ever treat this as a multiple single-writer streams as there is no important ordering between cache invalidations.
(Invalidations are self-contained facts; and the invalidations commute/are idempotent).</p>
<h3id="writing-to-streams"><aclass="header"href="#writing-to-streams">Writing to streams</a></h3>
<p>Writers need to track:</p>
<ul>
<li>track their current position (i.e. its own per-writer stream ID).</li>
<li>their facts currently awaiting completion.</li>
</ul>
<p>At startup, </p>
<ul>
<li>the current position of that writer can be found by querying the database (which suggests that facts need to be written to the database atomically, in a transaction); and</li>
<li>there are no facts awaiting completion.</li>
</ul>
<p>To reserve a stream ID, call <ahref="https://www.postgresql.org/docs/current/functions-sequence.html"><code>nextval</code></a> on the appropriate postgres sequence.</p>
<p>To write a fact to the stream: insert the appropriate rows to the appropriate backing table.</p>
<p>To complete a fact, first remove it from your map of facts currently awaiting completion.
Then, if no earlier fact is awaiting completion, the writer can advance its current position in that stream.
Upon doing so it should emit an <code>RDATA</code> message<supclass="footnote-reference"><ahref="#3">3</a></sup>, once for every fact between the old and the new stream ID.</p>
<h3id="subscribing-to-streams"><aclass="header"href="#subscribing-to-streams">Subscribing to streams</a></h3>
<p>Readers need to track the current position of every writer.</p>
<p>At startup, they can find this by contacting each writer with a <code>REPLICATE</code> message,
requesting that all writers reply describing their current position in their streams.
Writers reply with a <code>POSITION</code> message.</p>
<p>To learn about new facts, readers should listen for <code>RDATA</code> messages and process them to respond to the new fact.
The <code>RDATA</code> itself is not a self-contained representation of the fact;
readers will have to query the stream tables for the full details.
Readers must also advance their record of the writer's current position for that stream.</p>
<p>In a nutshell: we have an append-only log with a "buffer/scratchpad" at the end where we have to wait for the sequence to be linear and contiguous.</p>
<p>A fact might be expressed with 0 rows, e.g. if we opened a transaction to persist an event, but failed and rolled the transaction back before marking the fact as completed.
In principle a fact might be expressed with 2 or more rows; if so, each of those rows should share the fact's stream ID.</p>