<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Roman Vozzhenikov  on Medium]]></title>
        <description><![CDATA[Stories by Roman Vozzhenikov  on Medium]]></description>
        <link>https://medium.com/@vzroman?source=rss-01b863445a6e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*c_uCO9mM2tY-xAXb</url>
            <title>Stories by Roman Vozzhenikov  on Medium</title>
            <link>https://medium.com/@vzroman?source=rss-01b863445a6e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:41:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vzroman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[elock: scalable distributed locks with deadlock detection]]></title>
            <link>https://medium.com/@vzroman/elock-scalable-distributed-locks-with-deadlock-detection-e30c3c9a8c15?source=rss-01b863445a6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e30c3c9a8c15</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Roman Vozzhenikov ]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 11:03:37 GMT</pubDate>
            <atom:updated>2026-10-28T11:03:37.836Z</atom:updated>
            <content:encoded><![CDATA[<p>We have completed a large-scale SCADA/EMS project for KEGOC, Kazakhstan’s national electricity grid operator, that handles hundreds of thousands of signals per second. The project is based on our <a href="https://faceplate.io/">Faceplate</a> platform, which is built upon Erlang/OTP technologies, and we are sharing the experience and the solutions behind it one at a time. The <a href="https://medium.com/p/8e20f19c520d">first article</a> was about <a href="https://github.com/vzroman/ecall">ecall</a>, a small library that takes the traffic between nodes past the single distribution queue per node pair. This second one is about elock, the next piece: how the actors of such a system lock the data they write, what that costs at our scale, and how the design around the locks came to matter more than the lock engine itself. More will follow.</p><p><a href="https://github.com/vzroman/elock"><em>elock</em></a><em> is a lock library for Erlang: locks on any term, exclusive or shared, on one node or on several at once, with deadlocks detected across nodes.</em></p><figure><img alt="Locks per second on two nodes, 10,000 clients per node, ten shared local locks per transaction with no contention: elock 5.57 million per second, mnesia 211 thousand per second." src="https://cdn-images-1.medium.com/max/1024/1*RyjYuMvuq0e5gl2p0YgeQQ.png" /></figure><p>The runs behind every number here: two hosts with two Xeon Gold 6342 sockets each, 48 cores, hyper-threading off, a 10 GbE bond between them, one Erlang 27.2.2 node per host in a Docker container, driven by Common Test from a third machine. 10,000 clients per node unless said otherwise, over a pool of 5 million objects, 20 million locks per point. mnesia and global are in the tables as the two lock engines that ship with OTP. The suite is in the repository under test/performance.</p><h3>What elock does</h3><p>The library is small, and the part that decides the numbers is smaller.</p><p><strong>A lock is an ETS row, and a ticket is the only synchronization.</strong> A scope is a public ETS table. A lock on a term is a row in it: the term, the pid of its manager, and a counter. To ask for the lock, the caller increments the counter:</p><pre>lock(#request{scope = Scope, term = Term} = Request, OnQueued) -&gt;<br>  case ets:update_counter(Scope, Term, {3, 1}, {Term, 0, 0}) of<br>    1 -&gt;<br>      % the row was free: the caller holds the lock from this moment<br>      Manager = start_manager(Request),<br>      {ok, Manager};<br>    Ticket -&gt;<br>      % somebody holds it: queue behind them, in ticket order<br>      Manager = get_manager(Scope, Term, Ticket),<br>      Manager ! Request#request{ticket = Ticket, proxy = self()},<br>      wait_verdict(Manager, OnQueued, Request)<br>  end.</pre><p>Ticket 1 means the row was free: the caller holds the lock the moment the counter returns and spawns a manager for the term. Any later ticket means somebody holds it: the caller sends its request to the manager and waits for a verdict, locked, timeout or deadlock. The uncontended path is one atomic counter update in the caller, about 17 µs of scheduler time, and it is why both nodes were at 99.8 percent in the figure above: every core was taking locks, because nothing stood in the way. mnesia’s 11 percent in the same figure is its locker, one process per node, that every request calls whether the key is free or not.</p><p><strong>A manager per locked term, for as long as it is locked.</strong> The manager keeps the queue in ticket order and grants in that order. A shared request joins the shared holders at once only while nobody is waiting, so a stream of readers cannot starve a writer. When the last holder leaves and nobody waits, the manager deletes the row and exits. Contention on a hot term is one process on one scheduler; two hot terms are two processes on two schedulers.</p><p><strong>A request for several nodes is one worker per node.</strong> Each worker asks its node. All nodes are asked at once; the request holds the nodes that have granted it while it waits for the rest, and if any node fails the granted ones are released, so the result is all or nothing. A remote worker stays alive after the grant as the lock’s representative on the client’s node: it monitors the client and sends the release when the client exits.</p><p><strong>Deadlock detection.</strong> Only a request that has to wait while its process already holds something can deadlock, and only such a request pays for detection. It gets a graph worker, spawned when the manager reports it queued. The worker publishes the process’s holds into a wait-for graph that every node keeps in a public ETS table, and every new edge starts a walk from it, expanding locks on their own node and hopping to the other nodes with one cast per node. A walk that comes back to its origin has found a cycle, and the request of the younger context loses: it gets {error, {deadlock, Lock}}, keeps what it holds, and the caller decides, typically release and repeat. A walk has a limit on the locks it visits, past which the origin loses with probe_limit rather than let the walk become the cost.</p><p><strong>Locks die with their holder.</strong> A local holder is monitored by its manager, a remote one by its worker, and every node drops the locks of the clients of a node that has gone down. A process that crashes while holding locks leaves no lock behind.</p><h3>Distributed locks</h3><p>Now every write takes an exclusive lock on its key on both nodes, writes, releases: 10,000 clients per node with 1,000 transactions each, then 100,000 clients per node with 100 each, the same 20 million locks.</p><figure><img alt="Locks per second for one exclusive lock on both nodes per write, with the demand of 200,000 per second marked. At 10,000 clients per node: elock 95.6 thousand, mnesia 21.7 thousand, global 1.3 thousand. At 100,000 clients per node: elock 307 thousand, mnesia 15.8 thousand; global was not run." src="https://cdn-images-1.medium.com/max/1024/1*RBW-6iqHBGty57pADL6SKQ.png" /></figure><p>mnesia has three limits in its way, one behind the other: the locker, one process per node that every request goes through whether the key is free or not; the distribution queue, one per node pair, that every cross-node signal enters one at a time; and the wire. Ten times the clients gave it a quarter less throughput, 12 second transactions and 10 GB of memory per node. global’s set_lock is a cluster-wide protocol with retries: 16 seconds per lock, 4.4 hours for the run, and we did not run it with ten times the clients.</p><p>elock has no locker, and its cross-node traffic rides <a href="https://github.com/vzroman/ecall">ecall</a>, which enters the distribution queue once per batch rather than once per signal: ten times the clients gave three times the locks, and the batches got cheaper per lock as they grew. What is left is the wire. A cross-node lock is a round trip, 208 ms at 10,000 clients per node, and a client spends its time waiting for it while the nodes sit three quarters idle. More clients means more round trips in flight, not a shorter one.</p><p>elock can take the waiting out entirely, or cut it down a lot, but in the end that depends on the design of your system. The rest of this article is how we came to the 5.5 million figure in our production system.</p><h3>Our production system and its demand</h3><p>The system is the SCADA/EMS we built for KEGOC, Kazakhstan’s national electricity grid operator, described in the <a href="https://erlangforums.com/t/ecall-batched-pooled-send-cast-call-over-erlang-distribution-scales-past-the-single-output-queue-per-node-pair/5940/10">discussion</a> under the previous article.</p><p>The unit of information is a tag, much like a classic SCADA tag. Tags are data, not processes: records with a schema in a database engine that supports subscriptions, to a tag or to a query. The processes are the actors, the runtime services that read and write tags. The most typical of them:</p><ul><li><strong>A device connection.</strong> One process per connection to a field device, a PLC, an energy meter, any smart device. It receives updates from the device and writes them into the tags, and writes some points back, setpoints, PID settings and the like.</li><li><strong>A user script.</strong> It subscribes to its input fields, recalculates when they change, and writes the results to its output fields.</li><li><strong>An archive.</strong> It subscribes to its source tags and hands the values to a pool of writers in front of a time-sharded RocksDB store.</li><li><strong>A user session.</strong> One process per browser connection, subscribed to the tags on the open screen. A writer only when the user changes a setpoint or a setting.</li><li><strong>High-level services.</strong> The state estimation engine, prediction, the electricity grid graph, AI agents, the dispatcher assistant among them. Mainly consumers, with occasional writes back.</li></ul><p>A signal typically travels like this. A device connection reads its addresses and writes the values into its tags. A calculation or a user script subscribes to some of those tags and writes its results into tags of its own, and the archive and the alarm service subscribe to the results. Every heavy writer on that path owns the tags it writes, the tags of its device or the outputs of its script, and no two of them write the same tag. The occasional writers are off the path: a user session or the state estimation engine can subscribe to any tag and write to any tag.</p><figure><img alt="A PLC connection reads three device addresses and writes tag1 to tag3, an IoT connection writes tag4 to tag6. A calculation or user script subscribes to tag2, tag3 and tag4 and writes tag7 to tag9. The archive and the alarm service subscribe to tag9. Many more of each. Occasional writers, user sessions, state estimation, the grid graph, AI agents, subscribe to any tag and write to any tag, rarely." src="https://cdn-images-1.medium.com/max/1024/1*CiE-BaEncTVmagZLCmeIig.png" /></figure><p>A node runs a large population of such actors, each quiet until its device, its inputs or its user has something new, and most of them are both producers and consumers. A write does not stop at the node where it happened: it is shipped to the neighbouring nodes, and on every node the engine fans it out to the local subscribers. Actors have to synchronise over the tags they write, so there are locks, and every lock that spans nodes crosses the same channel as the writes.</p><p>The demand: a pool of 5 million real-time objects, about 10,000 actors per node over them, each writing about ten objects per second. That is 200,000 keys per second across the cluster, and the number every design below is measured against.</p><h3>Design 1: one exclusive lock on both nodes, per write</h3><p>We started with the simplest thing that is correct. Each actor, for each key it writes, takes an exclusive lock on both nodes, writes, releases. In the suite that is 10,000 clients per node with 1,000 transactions each, one key per transaction: 20 million locks.</p><p>elock gave 95,600 keys per second, under half of the 200,000 we need. mnesia gave 21,700, a tenth of it. global gave 1,265, with 16 seconds per lock and 4.4 hours for the run, and we did not run it again. None of them was short of CPU: elock left the nodes three quarters idle, because the clients were not computing. 20,000 of them were waiting for round trips, 208 ms each with elock, and the throughput was how many of those the link completed per second.</p><h3>Design 2: ten times the actors</h3><p>If the limit is the round trip, put more clients on it. We ran 100,000 clients per node with 100 transactions each, the same 20 million locks. elock scaled: 307,000 keys per second, the demand met with half as much again to spare, and the batches on the link got cheaper per lock as they grew. mnesia went backwards, to 15,800, with 12 second transactions and 10 GB of memory per node.</p><p>That was the first design to meet the demand, and we did not take it. Ten times the actors is not a parameter of our system, it is a rewrite of it: the device connections, scripts and archives would be split into pieces that have no reason to exist except to lock in parallel. And the capacity it left was thin.</p><h3>Design 3: batches, in random order</h3><p>The next idea was that writing in batches is cheaper, which for the store it is: one transaction of ten keys costs less than ten transactions of one. So we took our 10,000 clients back and let each of them lock ten keys exclusively on both nodes, write, release. A real actor may not know in advance which keys it will need, so the harness takes them in random order. 100 transactions per client, the same 20 million locks.</p><p>elock’s lock rate held, 88,300 keys per second, eight percent under design 1. Ten keys are still ten round trips, so a transaction took 2.2 seconds, 224 ms per key against 208: the batch bought the store something and the actor nothing. The eight percent is the chain. A transaction with six of its ten locks waiting for the seventh holds six keys that other transactions wait for, and they hold theirs. One percent of the transactions closed a cycle and were restarted; the rest paid for the chains, with the schedulers at 17 percent.</p><p>mnesia surprised us by speeding up, to 79,700, and stayed behind. Its locker prevents deadlocks instead of detecting them: a younger transaction asking for a lock held by an older one is restarted. Under random-order batches that rule fires constantly, and it restarted 30 percent of all transactions at a scheduler cost of 4 percent, because a restarted transaction does nothing but wait and try again. The harness makes a restart free. A production system does not: a restarted transaction has done its reads, perhaps its computation, and does them again.</p><p>Design 3 builds chains by construction, and a system that does that is not helped by an engine, however scalable. What had to change was the design of the system.</p><h3>Design 4: heavy writers lock locally, rare writers lock everywhere</h3><p>The next approach came from the shape of our own traffic, the picture above. About 99 percent of the writes come from the heavy runtime services, the device connections, the calculations, the user scripts, and each of them writes a set of tags that is known in advance and overlaps with no other service’s set: a PLC connection writes the tags of its PLC, a script writes its own outputs. The remaining percent comes from the occasional writers, a user changing a setpoint, the state estimation engine, the grid graph, an AI agent. Those can touch any tag, including the tags a heavy service owns, so the two kinds of writer still have to synchronise. Heavy services do not have to synchronise with each other at all.</p><p>So a heavy write does not need a lock that crosses the link. It needs a lock the occasional writer will run into, and the occasional writer can come to the service’s node for it. The one condition is that a service runs on one node at a time, so that there is one node to come to. How a service gets its node is a separate matter, below; for the numbers it only matters that it has one.</p><p><strong>Heavy writes under shared local locks, in batches.</strong> A service writes its tags under a shared lock on each key, on its own node only. Shared, because the only conflict a heavy write can have is with an occasional writer, and shared holders never wait for each other. Local, because that is where the occasional writer’s exclusive request will arrive. Between occasional writes, which is nearly always, the service’s shared requests are granted at once, by the caller itself.</p><p><strong>Occasional writes under exclusive locks on every node.</strong> An occasional writer takes an exclusive lock on each key it writes, on every node. On the heavy service’s node it queues behind the shared holders of that key and is granted when they release; the service’s next shared request on that key queues behind it. That is the whole synchronisation between the two kinds of writer, and it is paid by the rare one.</p><figure><img alt="Two nodes. On node 1 the PLC connection A, the heavy writer, writes k1, k2 and k3 under shared locks on node 1 only, granted at once. On node 2 a user session, the occasional writer, rarely writes k3 under an exclusive lock on every node; its request on node 1 queues behind the shared holder. Only the occasional write crosses the link." src="https://cdn-images-1.medium.com/max/1024/1*OhQv4dHcj5ODsXj3pa3rRw.png" /></figure><p>The heavy path in the suite: 10,000 clients per node, 100 transactions each, ten shared local locks per transaction on keys nobody else touches, which is what disjoint sets mean. The same 20 million locks, done in 3.6 seconds: 5.57 million keys per second, 28 times the demand, with no traffic on the link and both nodes 99.8 percent busy with the work the benchmark asked for. The 30 ms of a transaction is 10,000 runnable clients sharing 48 cores, not the locks. mnesia took 95 seconds for the same run, 211,000 keys per second at 11 percent busy: 10,000 clients queued behind its locker. The occasional path is design 1, 95,000 exclusive two-node locks per second, which for one percent of the traffic is a ceiling we will not see.</p><p>A third node, by the same reasoning, adds its own heavy capacity, since every heavy lock is local. What crosses the link is the occasional writers, which lock on every node and get slower by a node, and the service locks at start. We have not measured it, and it is the claim we would test first.</p><figure><img alt="Keys locked per second for the four designs, elock against mnesia, on a log scale with the demand of 200,000 per second marked: design 1 95.6k against 21.7k, design 2 307k against 15.8k, design 3 88.3k against 79.7k, design 4 5.57M against 211k." src="https://cdn-images-1.medium.com/max/1024/1*fNkIf780g0qcBGpkqZUJJw.png" /></figure><h3>Which node runs the service</h3><p>The condition in design 4, one node per service, is usually configuration: which service runs on which node, and a procedure for when that node is down. We wrote neither. Every node starts every configured service. On start, each service asks for an exclusive lock on its service object, the PLC connection object, the script object, on every node. The service that gets the lock keeps it and does the work for its set of tags. The service that does not get it waits inside the request, holding nothing. The request is a loop: when it returns an error, because a node went away, the service re-reads the ready nodes and asks again. One cross-node exclusive lock per service, once, at start.</p><figure><img alt="Two panels. At start, both nodes run a copy of PLC connection A and each asks for an exclusive lock A on every node; node 1’s copy holds it and works, node 2’s copy waits inside its request, holding nothing. When node 1 goes down, its locks are released, the waiting request on node 2 is granted and that copy continues the work." src="https://cdn-images-1.medium.com/max/1024/1*U846usU3iHXjiJN8BQ6uHg.png" /></figure><p>This decides none of the numbers above; a static assignment would have measured the same. It decided what we did not have to build. The work balances itself across the nodes: which node runs which service is decided by who wins the lock, and a node that is added takes the services whose locks it gets. And every service has a standby: when a service dies, or its node does, its locks are released, the partner on the neighbouring node that has been waiting inside its request gets the lock and continues the work. The retry loop and the property that locks die with their holder are the whole mechanism; there is no placement table and no failover code.</p><h3>Takeaways</h3><p>Every item here is the lede again: a granted lock costs microseconds, a waiting one costs the wait, and everything its holder holds waits with it.</p><ul><li><strong>Do not lock what does not need locking.</strong> The cheapest lock is the one you never take. A writer whose keys nobody else ever touches needs no lock on them at all. Look for such writers in your traffic first.</li><li><strong>Use the cheapest lock that is correct, above all on the common path.</strong> Shared local, exclusive local, exclusive across nodes, in that order. Put the common path on the lowest rung and move the expensive locks to the rare writers: in design 4 the occasional writer pays the cross-node exclusive lock so that the heavy ones never do.</li><li><strong>Keep the chains short.</strong> While you hold something, everybody behind it waits with you, on one node as on two. Do not hold a lock across a round trip or a long computation, and where you can, take the locks first and do the work after, so that a restart throws away a wait and not the work.</li><li><strong>Avoid deadlocks by construction.</strong> If the keys are known ahead, lock them in sorted order and a cycle cannot form. If they are not, as in design 3, expect cycles and price the restart honestly: it is free in a harness and never in production.</li><li><strong>Use elock :)</strong></li></ul><p>The library, with its performance suite, is at <a href="https://github.com/vzroman/elock">github.com/vzroman/elock</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e30c3c9a8c15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The many-to-one problem, one hop further: distributed Erlang under 150,000 senders]]></title>
            <link>https://medium.com/@vzroman/the-many-to-one-problem-one-hop-further-distributed-erlang-under-150-000-senders-8e20f19c520d?source=rss-01b863445a6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e20f19c520d</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Roman Vozzhenikov ]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 09:08:58 GMT</pubDate>
            <atom:updated>2026-10-21T09:08:58.636Z</atom:updated>
            <content:encoded><![CDATA[<p>We have completed a large-scale SCADA/EMS project for KEGOC, Kazakhstan’s national electricity grid operator, that handles hundreds of thousands of signals per second. The project is based on our Faceplate platform, which is built upon Erlang/OTP technologies. And now we are ready to share our experience and our solutions. We start with an article about a small library that solves a big problem.</p><p><em>OTP 25 fixed the lock that many local senders used to fight over. Send the same traffic to another node and a different single point takes its place: one distribution queue per node pair. This is the story of how a SCADA system ran into it, what it looks like in numbers, and what we built to get past it.</em></p><h3>The problem we all know: many senders, one process</h3><p>In 2021 Kjell Winblad described the <a href="https://www.erlang.org/blog/parallel-signal-sending-optimization/">parallel signal sending optimization</a> that shipped in OTP 25. The post starts from first principles: “All concurrently executing entities (processes, ports, etc.) in an Erlang system communicate using asynchronous signals.” Then it states the guarantee that makes the optimization possible: “The only signal ordering guarantee given is the following: if an entity sends multiple signals to the same destination entity, the order is preserved.”</p><p>Before OTP 25, every sender to a process appended to that process’s outer signal queue under one lock, and “this lock can become a scalability bottleneck and a contended hot-spot when there are enough parallel senders.” The fix hashes each sender onto one of 64 buffer slots, each with its own lock, so senders that are different entities stop synchronizing with each other. The receiver drains the slots in bulk. The buffers are installed only when a contention counter says they are needed, and only for processes running with {message_queue_data, off_heap}. In the post’s benchmark, receive throughput with 16 senders is 520 times better with the optimization.</p><p>Three ideas from that post carry over to everything below:</p><ol><li>The ordering guarantee is per sender-receiver pair. Different senders never needed to be serialized against each other.</li><li>The cure for a hot enqueue point is fewer contenders per lock, not a faster lock.</li><li>A receiver that drains in bulk is cheaper than one that pays for every message separately.</li></ol><h3>The problem we know less well: many senders, one remote node</h3><p>Now move the receivers to another node. Take 100,000 processes on node A, each sending to its own process on node B. At the application level there is no shared mailbox anywhere. At the transport level there is exactly one:</p><figure><img alt="Diagram: many senders on node A funnel into one distribution entry, one output queue, one lock, one port task, one TCP socket, one input handler on node B" src="https://cdn-images-1.medium.com/max/1024/1*Vtzzb7USnbunS7hU102onA.png" /></figure><p>With standard distribution, node A represents node B by a single DistEntry. Every RemotePid ! Msg encodes the message and then appends the encoded buffers to that entry’s output queue under the entry’s queue lock. One port task drains the queue into one TCP socket. On node B, one input handler parses every signal that arrives on that socket and routes it to its receiver. Adding receivers on B adds nothing on A. The structures are in <a href="https://github.com/erlang/otp/blob/OTP-27.2.3/erts/emulator/beam/erl_node_tables.h">erl_node_tables.h</a> and the send path in <a href="https://github.com/erlang/otp/blob/OTP-27.2.3/erts/emulator/beam/dist.c#L3510-L3606">dist.c</a>. If you run the lock profiler lcnt on such a node, the lock is listed as dist_entry_out_queue.</p><p>So the application topology can be many-to-many, and the transport is still many-to-one.</p><h4>What that looks like in numbers</h4><p>We measured plain distributed sends between two identical hosts: two Xeon Gold 6342 sockets each, 48 cores with hyper-threading off, 251 GiB of RAM, a 10 GbE bond between them, Ubuntu 22.04. Each node runs in a Docker container with host networking from the official erlang:27.2.2 image, stock emulator, default +zdbbl 1024. A third machine drives the run through Common Test.</p><p>The workload: N writer processes on node A, N receiver processes on node B, one receiver per writer. Every writer sends 1,000 messages and sleeps 100 ms between them, so the intended load is N × 10 messages per second and the ideal completion time is 100 seconds whatever N is. The message is a nested map (three sub-maps of ten atom fields each), 225 bytes on the wire. N goes from 10,000 to 150,000 in steps of 10,000. A point ends when the receivers have counted every expected message; nothing is dropped, a slow point is only a long one. Throughput is N × 1000 / elapsed seconds, where elapsed is the mean of each receiver’s first-to-last message span.</p><figure><img alt="Plain distributed send between two nodes, N writers at 10 messages per second each" src="https://cdn-images-1.medium.com/max/1024/1*_67hRS4C75YlnYuGvuBR3w.png" /></figure><figure><img alt="Native distributed send throughput against writer count. The line follows the intended pace up to 30,000 writers, drops at 40,000, and stays flat around 220,000 messages per second up to 150,000 writers." src="https://cdn-images-1.medium.com/max/1024/1*0UyYIsYX888XTSn6YL7eqg.png" /></figure><p>Up to 30,000 writers the node delivers what is asked of it. At 40,000 it delivers less than at 30,000. From there on, adding senders adds nothing: the plateau sits between 210,000 and 240,000 messages per second all the way to 150,000 writers, while the time to complete the fixed workload grows from 100 seconds to 11 minutes, the sender’s memory grows to 34 GB, and the run queues peak at tens of thousands of processes waiting for a scheduler. Peak memory here is erlang:memory(total) on the sender; about 2.2 GB of it is the process table for the harness’s large +P setting and is present in every point. “Scheduler busy” is the share of scheduler wall time not spent idle, which on this path also counts time schedulers spend blocked in the distribution machinery.</p><h4>Why more processes rather than a faster loop</h4><p>We could have taken a handful of processes and made them send as fast as possible. We chose to raise the number of processes and keep each one slow, because that is what a real system looks like. A process in our system owns a device, a subscription, or a calculation; it sends a message when it has something to say and does useful work in between. Load arrives as population, not as one tight loop. Sizing the test this way also exercises the parts of the runtime that matter at scale: scheduling tens of thousands of runnable processes, and flow control that has to suspend and resume every one of them.</p><h3>How we ran into it</h3><p>We built a SCADA/EMS system for a national electricity grid operator that processes hundreds of thousands of signals per second. A signal arriving on one node is not done when it is written locally: it also goes to neighbouring nodes, where it is fanned out to subscribers, fed into further calculations, and stored in the database.</p><p>At a certain load the system started to degrade, and not gracefully. Remote messaging slowed down first, but soon the whole VM was barely responsive. The investigation pointed at erpc:cast/4, which carried the inter-node traffic: it was consuming almost all the resources of the node. Our first thought was that erpc itself was the problem. Looking deeper showed that erpc was only using the same transport as everything else. Every message between two nodes, whether a plain send or an erpc spawn request, passes through the same distribution queue, and that queue was where the contention was.</p><p>The pattern resembled the many-to-one problem from Winblad’s post, but it had a different shape.</p><h4>Same shape, different lock</h4><p>When many local senders saturate an on_heap process, the node goes quiet. The scheduler statistics report the schedulers as busy, but the operating system shows one or two cores in use out of 48, because the schedulers are parked in the kernel waiting for a lock. In our distributed overload the opposite happened: top showed the BEAM at more than 4,600 % on a 48-core box. Every core was working, and almost nothing useful was getting done.</p><p>The difference comes from the locks. A process’s signal-queue lock is an ERTS process lock, and it does not allow barging: when it is released with a waiter queued, ownership is handed to the first waiter, which then has to be woken and scheduled before anything else can proceed. Under heavy fan-in that turns every enqueue into a wake-up, and throughput falls to the wake-and-dispatch rate. The distribution queue lock is a plain pthread mutex. It does allow barging: a running thread takes it the moment it is released, so the lock itself stays cheap even when almost every acquisition collides. We saw both regimes on the same box: 10,000 paced senders reached 12 % of their pace against one local on_heap process, and 99 % against a process on a second node over loopback. The distributed path does not collapse. It saturates.</p><p>What is expensive on the distributed path is not holding the mutex. It is the enqueue mechanics around it. Every unbatched signal is sized, allocated and encoded by the sending process, appended under the lock with the queue accounting updated, and then drained by the port task as a separate write. The cost is paid once per message, and it is paid by scheduler threads that could otherwise run your application.</p><h4>The long path</h4><p>The enqueue path gets much longer once the queue is saturated. The distribution buffer busy limit, +zdbbl, is 1 MiB by default. When the encoded bytes waiting in the output queue reach it, the queue is flagged busy and every sender that arrives after that takes the long way round:</p><ol><li>Append the encoded message under the queue lock, then see the busy flag and release the lock.</li><li>Allocate a list entry for itself and suspend itself, which means taking its own status lock and leaving the run queue.</li><li>Take the queue lock a second time to check whether the queue is still busy, and if it is, append itself to the entry’s list of suspended processes. If the queue emptied in between, resume immediately, but still yield the scheduler as if it had been suspended.</li><li>Later, after the port task has written the queued buffers to the socket and the queue has dropped below the limit, the port task detaches the whole suspended list and resumes every process in it, one after another: process lookup, status lock, state update, run-queue insertion, list entry release.</li></ol><p>All of that is at <a href="https://github.com/erlang/otp/blob/OTP-27.2.3/erts/emulator/beam/dist.c#L3549-L3606">dist.c</a> and its drain counterpart a few hundred lines <a href="https://github.com/erlang/otp/blob/OTP-27.2.3/erts/emulator/beam/dist.c#L4023-L4037">further down</a>. It is a sensible design for a few processes hitting a slow link. With 100,000 processes it becomes the workload. Each cycle suspends and resumes a herd, the herd refills the queue in a few milliseconds, and the cycle repeats. That is where the 4,600 % went: encoding, suspending, resuming, and scheduling a herd, tens of times per second.</p><h4>What we tried first</h4><p>We raised +zdbbl. The <a href="https://www.erlang.org/doc/apps/erts/erl_cmd.html">documentation</a> says “a higher limit gives lower latency and higher throughput at the expense of higher memory use”, and that is what a knowledgeable colleague suggests first. It changed the shape of the overload, not its size. With a huge limit the node alternates between long quiet stretches with every writer suspended and bursts where all of them wake at once: a saw-tooth on the CPU graph with a period of tens of seconds, and memory climbing with every cycle. Throughput at the end was the same.</p><p>We tried process_flag(async_dist, true), which makes senders never block on the busy limit. The <a href="https://www.erlang.org/doc/apps/erts/erlang.html#process_flag_async_dist">documentation</a> is candid about it: no flow control is enforced, and “unlimited signaling with async_dist enabled in the absence of flow control will typically cause the sending runtime system to crash on an out of memory condition.” That is what we got: memory grew until the VM was killed. Removing the suspension removes nothing from the per-message work; it only removes the brake.</p><h4>Batching, then a pool, then ecall</h4><p>Then we tried the approach from Roberto Ostinelli’s 2009 post <a href="https://www.ostinelli.net/boost-message-passing-between-erlang-nodes/">Boost message passing between Erlang nodes</a>: a router process per node that accumulates messages for a remote node and forwards them in one go. He measured 5.3 million messages per minute inside a node against 700,000 between nodes, and batching took the remote figure to 2.1 million. His router flushed on a queue size or a 200 ms timer. We kept the batching and dropped the timer: the router shipped whatever it had, immediately.</p><p>That gave good results, and it was still not enough. One process sends on one scheduler. At a certain load it could no longer keep up with what the writers were pushing into its mailbox, and the mailbox started to grow. So we replaced the single router with a pool of senders on one side and a pool of receivers on the other. That solution satisfied our demand.</p><p>Which brought us back to the original problem. Our traffic was erpc:cast, and there was no way to make erpc travel through our transport. So we implemented ecall: the pooled, batched transport, with cast and call built on it as different kinds of batch elements. It solved our problem. Then we built the multi-node call and cast patterns that a distributed system needs, call_one, call_any, call_all, call_all_wait, cast_one, cast_all, on top of it.</p><h3>What ecall does</h3><p>The library is small. When a connection to a remote node exists, ecall:send(To, Msg) does not send to To from the caller. It picks a local proxy by hashing the caller’s pid over the pool and hands the request to it:</p><pre>pick_worker(#connection{size = Size, pool = Pool}) -&gt;<br>  I = erlang:phash2(self(), Size),<br>  maps:get(I, Pool).<br> <br>Proxy ! {do, {send, RemoteTo, Message}}</pre><p>The proxy loop is the whole idea in a dozen lines:</p><pre>worker_loop(Remote, BatchSize) -&gt;<br>  erlang:garbage_collect(self()),<br>  Requests = collect_requests(0, BatchSize),<br>  catch Remote ! {batch, Requests},<br>  worker_loop(Remote, BatchSize).<br> <br>collect_requests(0, BatchSize) -&gt;<br>  receive<br>    {do, Request} -&gt; [Request | collect_requests(1, BatchSize)]<br>  end;                                   % nothing waiting: block<br>collect_requests(Count, BatchSize) when Count &lt; BatchSize -&gt;<br>  receive<br>    {do, Request} -&gt; [Request | collect_requests(Count + 1, BatchSize)]<br>  after<br>    0 -&gt; []                              % mailbox empty: ship what we have<br>  end;<br>collect_requests(_Count, _BatchSize) -&gt;<br>  [].                                    % batch cap reached</pre><p>Remote is one worker of the receiver pool on the other node, paired with this proxy. It replays the batch locally:</p><pre>handle_batch([{send, To, Message} | Rest], State) -&gt;<br>  catch To ! Message,<br>  handle_batch(Rest, State);<br>handle_batch([{cast, Module, Function, Args} | Rest], State) -&gt;<br>  spawn(Module, Function, Args),<br>  handle_batch(Rest, State);<br>handle_batch([{call, Ref, ClientPid, Module, Function, Args} | Rest], State) -&gt;<br>  spawn(fun() -&gt;<br>    try<br>      Result = apply(Module, Function, Args),<br>      ecall_connection:send(ClientPid, {Ref, Result})<br>    catch<br>      _:Reason -&gt; ecall_connection:send(ClientPid, {&#39;DOWN&#39;, Ref, Reason})<br>    end<br>  end),<br>  handle_batch(Rest, State);<br>handle_batch([], State) -&gt;<br>  State.</pre><p>The principles behind it, in the order they mattered to us:</p><h4>1. Batching: fewer enqueues, more messages per enqueue</h4><p>The distribution queue is entered once per batch instead of once per message. A batch of 20 messages pays for one encode of a top-level signal, one lock acquisition, one queue append and one socket write. This is Ostinelli’s principle taken further: no timer, a pool instead of one router, and the batch used for more than plain sends. It also costs fewer bytes: the distribution header and control message are paid once per batch, so at 150,000 writers the same 150 million messages went over the wire as 25.4 GB instead of 33.8 GB, 170 bytes per message instead of 225.</p><h4>2. A pool of senders and receivers instead of one process</h4><p>One batching process is a new single point, on both ends: one process collecting and encoding batches, one process decoding them and doing the local deliveries. A pool spreads that work over the cores. The receiver pool defaults to erlang:system_info(logical_processors) on the receiving node, 48 on our hosts, and a connection creates one local proxy per remote worker. Callers are sharded onto proxies by pid, so the whole pool works in parallel with no coordination between its members.</p><p>We swept the pool size in an earlier series of runs on the same hosts, up to 400,000 writers. A pool of one never stalled but saturated badly: 14 % of the intended pace and 69 GB of sender memory at 400,000 writers. A pool of 8 held to about 150,000 writers and fell off after that. Pools of 24 and 48 were flat across the whole range.</p><h4>3. Self-balancing batching: bigger batches are cheaper, and more backpressure makes bigger batches</h4><p>The after 0 is the important line. The proxy never waits for a batch to fill. It blocks only when it has nothing at all; once it has one request, it takes whatever else is already in its mailbox and ships. So the batch size is not a configured number. It is the current backlog.</p><p>At low load the mailbox is nearly always empty, a batch holds one or two messages, and the cost of the funnel is one local hop. Under pressure the backlog grows, batches grow with it, and each distribution enqueue carries more messages. Backpressure from the distribution layer feeds the same loop: when a proxy is suspended on the busy limit, its callers keep filling its mailbox, and when it resumes it ships everything that accumulated as one batch. The busy limit is the batching clock. This is why we leave +zdbbl at its default for the pooled path; raising it in our earlier runs only made the batches smaller and the memory larger.</p><p>The socket counters show the balancing at work. Average bytes per distribution socket write, send test:</p><figure><img alt="Average bytes per distribution socket write, send test" src="https://cdn-images-1.medium.com/max/1024/1*oo5cggT27kQ2XXD_Z2Tg9w.png" /></figure><p>Native is one message per write by construction. ecall grows from about two messages per write to about twenty, while its throughput stays at the intended pace. The batch cap of 1,000 is far above anything these runs produced. It exists as a safety valve, not as an operating point.</p><h4>4. {message_queue_data, off_heap} for the pools</h4><p>A proxy’s job is to hold a backlog, and that decides how its mailbox should be stored. With the default on_heap, queued messages end up on the process heap and every garbage collection walks them. A proxy sitting on thousands of queued requests pays for all of them at each collection, and the price grows with the backlog. With off_heap the queue lives outside the heap and is never part of a collection. The <a href="https://www.erlang.org/doc/apps/erts/erlang.html#process_flag_message_queue_data">process_flag documentation</a> says the same: off_heap is recommended for a process that “may potentially accumulate a large number of messages in its queue”, because collecting a heap that holds them “can become extremely expensive”. Both pools are therefore spawned with:</p><pre>spawn_opt(fun() -&gt; worker_loop(Remote, BatchSize) end,<br>          [link, {message_queue_data, off_heap}])</pre><p>The explicit garbage_collect/1 at the top of the proxy loop is the other half of it. It runs at the one moment the proxy holds nothing, so it is nearly free, and it releases the batch that was just sent.</p><p>Contention on the proxy mailboxes is a smaller concern than it looks. The hop from 150,000 writers into 48 proxies is a many-to-one send on paper, but only scheduler threads write, there are 48 of them on this box, and they are sharded over 48 mailboxes: at any instant that is about one writer per mailbox. The OTP 25 signal-queue buffers from Winblad’s post, which come with the off_heap flag, are additional protection for the case where the pool is much narrower than the scheduler count. Our earlier pool-size runs show where that matters: a pool of one with off_heap proxies completed 100,000 writers in 313 seconds, and the same point with the flag switched to on_heap did not complete at all, one core busy out of 48 and 107 of 112 VM threads parked in the kernel. With a pool the size of the scheduler count that protection is rarely exercised. The garbage-collection saving is what you get every day.</p><h4>5. Casts and calls over the same transport</h4><p>A batch element is a tagged tuple, so cast and call cost the transport nothing extra. A cast becomes a spawn/3 on the remote worker; a call becomes a spawned process that applies the function and sends the result back to the caller through the pooled channel in the opposite direction, so both legs are batched. If no ecall connection exists for the target node, the calls fall back to !, erpc:cast/4 and erpc:call/4. Nodes running ecall find each other through a pg group and connect automatically. Failure semantics match the native operations: send and cast are fire-and-forget on both paths, and a call monitors its proxy, which is linked to the connection and exits when the connection to the node goes down, so the caller gets {error, {badrpc, Reason}} instead of waiting forever.</p><pre>ecall:send(RemotePid, Msg),                               % instead of RemotePid ! Msg<br>ok = ecall:cast(Node, Module, Function, Args),            % instead of erpc:cast/4<br>{ok, Result} = ecall:call(Node, Module, Function, Args).  % instead of erpc:call/4</pre><h4>6. Multi-node patterns</h4><p>Replication and lookup need policies about which nodes and how many answers, so those sit on top:</p><ul><li>cast_one(Nodes, M, F, As): fire and forget at one node, the local node if it is in the list</li><li>cast_all(Nodes, M, F, As): fire and forget at every node</li><li>call_one(Nodes, M, F, As): try nodes one at a time until one answers {ok, _}</li><li>call_any(Nodes, M, F, As): ask all nodes in parallel, take the first {ok, _}</li><li>call_all(Nodes, M, F, As): require every node to answer {ok, _}</li><li>call_all_wait(Nodes, M, F, As): collect both the replies and the rejects</li></ul><p>A called function returns {ok, Result} or {error, Reason}; the group functions decide what to do with each answer. Nodes that are unreachable come back as {badrpc, Reason}, ignored by default and treated as errors with the optional fifth argument. That is the vocabulary a distributed database needs: write to all, read from any, fall back on error.</p><h3>The numbers</h3><p>Same hosts, same matrix, three operations: ! against ecall:send/2, erpc:cast/4 against ecall:cast/4, and erpc:call/4 against ecall:call/4. The ecall path ran with the defaults: a pool of 48, batch cap 1,000, +zdbbl 1024. For casts, the cast function is erlang:send to a counter process on node B, so a point completes only when every cast has executed remotely. For calls, each writer waits for its reply before sleeping, so a slow reply stretches that writer’s cycle. Elapsed for cast and call is wall time from releasing the writers to verified completion.</p><p>Send:</p><figure><img alt="Send: native ! against ecall:send, messages per second" src="https://cdn-images-1.medium.com/max/1024/1*tPCqAD6grUBsiw_NeeM-oA.png" /></figure><figure><img alt="Send throughput against writer count for native distribution and ecall. Native flattens at about 220,000 messages per second after 30,000 writers; ecall follows the intended pace to 1.48 million messages per second at 150,000 writers." src="https://cdn-images-1.medium.com/max/1024/1*ttC3s7MFExThMZOrmQr85Q.png" /></figure><p>Below the knee the two paths are indistinguishable: the funnel costs nothing measurable. Above it, ecall keeps following the intended pace, 98.8 % of it at 150,000 writers, which means the test’s own pacing was the limit at the top of the sweep, not the transport. The same 150 million messages took 659 seconds natively and 101 seconds through the pool.</p><p>Cast:</p><figure><img alt="Cast: erpc:cast against ecall:cast, casts per second" src="https://cdn-images-1.medium.com/max/1024/1*BTMKaTU8-PsnTNuVgviVmw.png" /></figure><p>Call:</p><figure><img alt="Call: erpc:call against ecall:call, calls per second" src="https://cdn-images-1.medium.com/max/1024/1*dlAtc0ySen8pzwPxAcgVTA.png" /></figure><figure><img alt="Cast and call throughput against writer count, native and ecall, as two panels on the same scale. erpc:cast stays near 100,000 per second and declines; ecall:cast reaches 1.19 million per second. erpc:call declines from 110,000 to 65,000 per second; ecall:call reaches 403,000 per second." src="https://cdn-images-1.medium.com/max/1024/1*YxJS6-peh6y9Of0rfedxcQ.png" /></figure><p>This is the production symptom, reproduced. The native cast path is the worst of the three: it never scales past about 118,000 casts per second and declines from there, because an erpc:cast is not a message but a spawn request, which is heavier on both ends of the channel. The pooled path carries a batch of casts as one signal, and the 48 workers on node B do the spawning in parallel. At 120,000 writers, 82,000 casts per second became 990,000, and the same 120 million casts finished in 121 seconds instead of 1,459.</p><p>Calls are the hardest case for any transport, because every writer has one call in flight and waits for the round trip. Both paths peak much lower than send. ecall still delivers six times the calls per second at the top of the sweep, at 27 % of the intended pace where erpc:call is at 4 %. We have not yet profiled where the rest of the round trip goes on the call path; that is the next thing to look at.</p><h3>The resource bill</h3><p>Throughput was only half of our problem. The other half was a node that had no resources left for anything else. At 150,000 writers:</p><figure><img alt="The resource bill at 150,000 writers" src="https://cdn-images-1.medium.com/max/1024/1*CW2ICGGdPZ87JM5dFa25YQ.png" /></figure><p>The ecall memory line is flat across the sweep: 2.3 GB at 10,000 writers, 3.3 GB at 150,000, growing with the number of processes and not with the backlog. The native line grows with the backlog. In an earlier instrumented run on the same hosts, almost all of the native sender’s memory sat in the binary allocator: encoded distribution output buffers waiting for the port task. The busy limit does not bound that memory; we measured tens of gigabytes of it against a 1 MiB limit.</p><p>The scheduler figures are shares of scheduler wall time, not CPU seconds, and on the native path they include time spent blocked in the distribution machinery. Normalized by the work done, the difference is larger than the raw percentages suggest. Scheduler time per million operations, computed as busy share × 48 schedulers × elapsed / millions of operations:</p><figure><img alt="Scheduler time per million operations" src="https://cdn-images-1.medium.com/max/1024/1*mUHywWuCNN_bAhG9N_pNKA.png" /></figure><p>The run-queue column is the one we find most telling. On the native send path 76,000 processes were runnable at once, waiting for a scheduler; on the pooled path, 1,185. A node in the first state has no capacity left for the work the messages were about.</p><p>The network is not the limit in either case. At 150,000 writers the native send path wrote 51 MB/s to the distribution socket; ecall wrote 251 MB/s to the same socket, and a 10 GbE link carries about 1,250 MB/s.</p><h3>What it costs</h3><p>None of this is free, and it is better to say so than to have it pointed out.</p><ul><li><strong>Backpressure moves.</strong> A native remote send suspends the caller when the channel is busy. ecall:send/2 and ecall:cast/4 return as soon as the request is in a local proxy mailbox. The proxies are flow-controlled; the callers are not. Under sustained overload with no application-level admission control the proxy mailboxes grow without bound; the pool of one at 400,000 writers and 69 GB is what that looks like. Queues do not fix overload. They give you a much higher ceiling and a place to put the policy.</li><li><strong>Ordering is preserved per caller.</strong> A caller always maps to the same proxy, a proxy emits batches in order, and the worker replays each batch in order. That is exactly Erlang’s guarantee, no more: nothing is promised about the interleaving of different callers, and cast and call bodies run in independent processes with no ordering at all.</li><li><strong>One more hop each way.</strong> Two extra scheduling events and one extra local copy per message. Invisible above the knee, measurable below it: at 10,000 writers the call path shows slightly higher scheduler utilization through ecall than through erpc.</li><li><strong>Measurement limits.</strong> One run per point, one payload of 225 bytes, no large binaries, sender-side metrics only, and for the send test an elapsed time averaged over receivers. The pacing loop stretches when an operation is slow, so intended rates are demand targets, not a fixed arrival rate. The knee at 30,000 to 40,000 writers is a property of this workload and this hardware, not a constant of Erlang.</li></ul><h3>Takeaways</h3><ul><li><strong>Count your writers, not your messages.</strong> Distribution has one queue and one lock per node pair, whatever the number of receivers. The cost of that queue is driven by how many things enter it and how often, not by the bytes they carry.</li><li><strong>Batch before the queue, not after it.</strong> TCP can coalesce bytes already handed to the socket, but the per-signal work happens before that. A batch of twenty messages is one encode, one enqueue, one write, and fewer bytes.</li><li><strong>Never wait for a batch to fill.</strong> receive … after 0 takes what is already there. Low load pays one hop; high load gets big batches, because the backlog is the batch, and the runtime’s own backpressure is the clock.</li><li><strong>Pool both ends.</strong> One batcher is a new single point.</li><li><strong>Make the pool processes off_heap.</strong> A process whose job is to hold a backlog should not garbage-collect it. The OTP 25 buffers come with the same flag, as extra protection when the pool is narrow.</li><li><strong>erpc is not the problem, and it is not the fix.</strong> It uses the same channel. Anything that must scale between two nodes needs its own transport policy above distribution, because the runtime does not shard this queue for you.</li></ul><p>The library, with its performance suite, is at <a href="https://github.com/vzroman/ecall">github.com/vzroman/ecall</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e20f19c520d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>