---
title: 'A Trade Server Built in <em>Rust</em>: From Shared Memory to the Socket'
tags:
  - backend
  - rust
  - finance
  - networking
  - design-patterns
published: true
date: 2026-12-03 16:02:00
series: 'Building a Stock Trade WebSocket Server'
seriesOrder: 3
description: 'How I built a Rust server that links the process receiving trades and the process accepting connections through a shared-memory ring buffer, then sends frames out through a subscription index and per-connection queues. It covers the conditions a ring buffer must keep under concurrent access and restarts, the policy of disconnecting slow clients, and the results of comparing against a capture.'
art:
  undraw: local-server
---

> The server in this series is one I built myself for learning. I did not refer to any company's private source code, and it has nothing to do with the code or systems of the company I work for. The only sources were frames anyone can observe in a browser, public documents, and open source.

With the server up and one client receiving Samsung Electronics trades, I killed the process that produces trades with `kill -9`. The frames arriving at the client stopped. When I started that process again 3 seconds later, frames began arriving again. The WebSocket connection was not dropped in between, and the `message-id` number continued from 86 to 87.

In [Part 2](/2026/11/websocket-trade-server-path-and-os-basics) I drew the path a single trade takes. This time I follow that path through code. It is a server that links the `feed`, which produces trades, and the `gateway`, which accepts connections, through shared memory, then finds the subscribers and sends them frames. It does not reproduce the internals of any particular brokerage. It is a structure I decided on myself, based on public frames.

> The server code is in [yceffort/ws-trade-server](https://github.com/yceffort/ws-trade-server), and quotes are based on commit [`47563840`](https://github.com/yceffort/ws-trade-server/tree/47563840775daf4ac94ab106452730e7beac9a28). I used Rust 1.95.0, tokio 1.54.1, tokio-tungstenite 0.30.0, and prost 0.14.6, and all experiments and measurements were done on macOS on an Apple M5 (10 cores). The commands I ran for each experiment are in the footnotes.
>
> Since then I have added experiments such as authentication, connection limits, and shutdown notices to the repository, and I have also changed the log format, so the latest code differs in shape from the code and log output quoted in this post.

## Table of Contents

## What Splitting Into Two Processes Gives You

The server is made of two executables. The `feed` produces trades and writes them to shared memory, and the `gateway` accepts WebSocket connections and sends out the trades it reads from shared memory. In a real service the `feed` would receive trades from an exchange, but there is no exchange here, so the `feed` generates arbitrary trades for each stock.

I ran the opening experiment as follows. I started the `gateway` and the `feed`, and had one client subscribe to Samsung Electronics trades and print one line per second with what it received.[^1] At 4.5 seconds after the start I killed the `feed` with `kill -9`, and at 7.5 seconds I started it again. Each line prints three values.

- **Count (건수):** The number of trade frames received during that 1 second. The `feed` picks the interval until the next trade at random for each stock, so the count differs from second to second even while the `feed` is alive.
- **Sequence number (순번):** The `message-id` header of a trade frame has the form `connection ID-number`, and the sequence number is the number after the dash. The `gateway` assigns it per connection, incrementing from 1, so if a connection drops and reconnects it starts again from 1. The output prints the sequence number of the last frame received during that 1 second.
- **Sequence gaps (순번 빠짐):** The number of numbers between 1 and the last sequence number that were not received.

```text
1초: 1초 동안 17건, 마지막 순번 17, 순번 빠짐 0
2초: 1초 동안 18건, 마지막 순번 35, 순번 빠짐 0
3초: 1초 동안 22건, 마지막 순번 57, 순번 빠짐 0
4초: 1초 동안 24건, 마지막 순번 81, 순번 빠짐 0
# 4.5초: feed를 kill -9로 종료
5초: 1초 동안 5건, 마지막 순번 86, 순번 빠짐 0
6초: 1초 동안 0건, 마지막 순번 86, 순번 빠짐 0
7초: 1초 동안 0건, 마지막 순번 86, 순번 빠짐 0
# 7.5초: feed를 다시 실행
8초: 1초 동안 7건, 마지막 순번 93, 순번 빠짐 0
9초: 1초 동안 11건, 마지막 순번 104, 순번 빠짐 0
```

The two lines starting with `#` were added for explanation and are not in the real output. Adding up the counts from the first line to any given line gives that line's last sequence number, so no number was missed. The 5 in the 5-second line are trades the `feed` wrote before it died, and not a single trade arrived in the 6-second and 7-second lines. The first frame received after I started the `feed` again had sequence number 87, not 1. If the connection had dropped and reconnected, the sequence would have restarted from 1, so this number confirms that the same WebSocket connection stayed up during the 3 seconds the `feed` was dead.

The `gateway` left a single log line during the same time.

```text
seq가 326에서 1로 작아졌다. feed가 다시 뜬 것으로 본다
```

(The log says "seq went down from 326 to 1. I take it that the feed came back up.") Here `seq` is a different number from the sequence number the client sees. It is an internal number the `feed` attaches each time it writes a trade to shared memory, and it is assigned one at a time in order to the trades of all stocks regardless of subscription, so it is larger than the 86 trades the client received. When the `feed` is started again, this number restarts from 1, and the `gateway` took the number getting smaller as a sign of a restart.

<LiveDemo src="/demos/websocket-trade-server-rust-implementation/index.html?view=restart&lang=en" title="How the connection and the numbers change when the feed is killed with kill -9 and started again 3 seconds later" height={500} />

The connection continued, but the data did not. When it restarts, the `feed`'s generator resets prices to their initial values and accumulates cumulative volume and cumulative trading value from 0 again. There is also no feature to recover the trades from the 3 seconds it was down. The `gateway` sends a heartbeat every 5 seconds regardless of whether the `feed` is alive, so the client cannot tell those 3 seconds from a time when there were no trades. The "순번 빠짐 0" (sequence gaps 0) in the output above only confirms the continuity of the numbers assigned within the connection. Whether the connection is maintained and whether trades are received without gaps have to be checked separately.

## The Message That Crosses Between Processes

The format the two processes write to and read from shared memory has to be decided first. I could use the JSON that goes out to clients as is, but I decided on a separate internal format, protobuf. Protobuf is a serialization format in which the shape of a message is written first in a `.proto` file, and values are converted to bytes according to that definition. I based the field layout on the frames I observed and made up the types and names myself.

### Two Looks at the Same Trade

If you print the same trade as protobuf and as JSON, the difference is immediately visible.[^2]

```text
protobuf 레코드 63바이트
08 01 10 01 1a 07 41 30 30 35 39 33 30 20 ae fc
c0 a4 9f 34 28 01 30 01 3a 03 4b 52 57 42 04 08
98 c4 08 4a 04 08 e0 c5 08 50 09 58 02 60 02 6a
06 08 a6 8d 01 10 02 70 09 7a 04 08 d8 e5 4c

JSON 본문 248바이트
{"code":"A005930","dt":"2026-11-19T16:07:36Z","currency":"KRW","exchange":"krx","session":"REGULAR","base":70000,"close":69900,"volume":9,"tradeType":"SELL","changeType":"DOWN","tradingStrength":90.43,"cumulativeVolume":9,"cumulativeAmount":629100}
```

(The two labels read "protobuf record, 63 bytes" and "JSON body, 248 bytes".) JSON writes the key names out as characters every time. Protobuf writes only the field numbers given in the `.proto` file, and the program reading it knows the names from the definition. Decoding a few of the bytes gives the following.

| Bytes                        | Meaning                                                          | The same content in JSON                    |
| ---------------------------- | ---------------------------------------------------------------- | ------------------------------------------- |
| `08 01`                      | Value 1 of field 1 (`seq`)                                       | An internal number that is not in the frame |
| `1a 07 41 30 30 35 39 33 30` | Field 3 (`code`), length 7, the characters `A005930`             | `"code":"A005930",` 17 bytes                |
| `42 04 08 98 c4 08`          | Field 8 (`price`), the integer inside is 69900                   | `"close":69900,` 14 bytes                   |
| `58 02`                      | Value 2 (sell) of field 11 (`side`)                              | `"tradeType":"SELL",` 19 bytes              |
| `6a 06 08 a6 8d 01 10 02`    | Field 13 (`trading_strength`), the integer 9043 and a scale of 2 | `"tradingStrength":90.43,` 24 bytes         |

The fields in the example above each start with a 1-byte tag holding the field number and type. The tag is also a variable-length integer, so a field number of 16 or more needs 2 or more bytes. Integers and enums also vary in length with their value.[^3] The integer inside `Decimal` is encoded with the ZigZag method (`sint64`) so that negative numbers are short too, so a positive number is written as twice its actual value. Reading `98 c4 08` in the table as is gives 139,800, and the price is half of that, 69,900. For this trade the protobuf is 63 bytes, about a quarter of the 248-byte JSON body. Compared with 372 bytes including the STOMP headers it is about a sixth, but for choosing an internal storage format, the comparison with the JSON body is more direct. The space a record actually takes in the ring also includes the length field and alignment padding that I look at later.

The `feed` and the `gateway` generate Rust types from the same `.proto` file. Using a field that does not exist is caught at compile time. But the compiler does not check the compatibility of two processes built from different versions. In that case you have to decide separately how to change field numbers and types.

### Price as Two Integers

The type that holds a price is as follows.[^4]

```proto
// 값 = units / 10^scale. 예: 150.96은 units 15096, scale 2
// 부동소수점을 거치지 않으려고 정수와 자릿수로 나눴다.
message Decimal {
  sint64 units = 1;
  uint32 scale = 2;
}
```

Among the `tradingStrength` values I saw in Part 2, some had 19 significant digits. Trading strength is a different value from price, but I used the same `Decimal` type for both so that decimal digits are preserved. A `double` cannot represent all such values exactly. JavaScript's `0.1 + 0.2` becoming `0.30000000000000004` is also due to the representational limits of binary floating point. Here I store a value split into an integer (`units`) and a decimal point position (`scale`). For example, 90.43 becomes 9043 and 2. Since `units` is an `i64`, this method also holds only values within the integer range.

The digits also have to be preserved when sending out JSON. If you convert the integer to `f64`, divide by a power of 10, and then serialize, the output is already a rounded value. You can see the difference with the following 19-digit value.

```text
정수와 자릿수 그대로: 104.2857142857142857
f64를 거친 값: 104.28571428571429
```

(The two labels read "integer and scale as they are" and "value that went through f64".) The `gateway` does not divide. It inserts the decimal point between the digit characters.[^5]

```rust
// units / 10^scale을 f64를 거치지 않고 자릿수 그대로 JSON 숫자로 쓴다. units 15096, scale 2는 150.96이다.
fn number(decimal: &Decimal) -> Box<RawValue> {
    let digits = decimal.units.unsigned_abs().to_string();
    let sign = if decimal.units < 0 { "-" } else { "" };
    let scale = decimal.scale as usize;
    let text = if scale == 0 {
        format!("{sign}{digits}")
    } else {
        // 정수부가 한 자리는 남도록 앞을 0으로 채운다. units 5, scale 2는 0.05다.
        let digits = format!("{digits:0>width$}", width = scale + 1);
        let (whole, fraction) = digits.split_at(digits.len() - scale);
        format!("{sign}{whole}.{fraction}")
    };
    RawValue::from_string(text).expect("부호와 숫자, 소수점으로만 만든 글자는 JSON 숫자다")
}
```

`RawValue` is a type that holds a piece of valid JSON. Here I put in the number string I built myself and output it as an unquoted JSON number like `"close":150.96`. Even if the server preserves the digits, the browser's `JSON.parse` can lose precision when it converts to `Number`. As I confirmed in Part 2, the value above shrinks to 17 digits. A client that needs the original digits should also consider something like a parser that preserves number tokens.

## The Shared-Memory Ring Buffer

I covered in Part 2 that when two processes connect the same file with `mmap`, they see the same memory. What remains is how to divide up and use that memory. The structure I chose is a ring buffer with one writing process and several reading processes. When the writing process reaches the end, it goes back to the start and overwrites old data, and it does not wait for the reading processes. This is because one slow `gateway` must not stop the `feed`.

<LiveDemo src="/demos/websocket-trade-server-rust-implementation/index.html?view=ring&lang=en" title="The structure of the ring file. After a 64-byte header, records aligned to 8-byte boundaries follow one after another" height={500} />

Positions are counted as the total number of bytes written so far. The actual position in the data area is the remainder of dividing this number by `capacity`. `tail` is the position where writing has finished, and each reading process keeps the position it has read up to in its own memory. Because the read position is not written into the ring, the writing process does not have to manage state for each reading process or wait for them to finish. The cache and memory access costs when several processes read together have to be considered separately.

### The Ring as a File

I checked the picture against actual bytes. I made the data area small, 8,192 bytes, had it write the trades of a single stock, and then read the start and end of the data area.[^6]

```text
$ xxd -s 64 -l 72 ring
00000040: 4100 0000 0872 1001 1a07 4130 3035 3933  A....r....A00593
00000050: 3020 8586 c2a4 9f34 2802 3001 3a03 4b52  0 .....4(.0.:.KR
00000060: 5742 0408 e8a1 084a 0408 e0c5 0850 0458  WB.....J.....P.X
00000070: 0160 026a 0608 96db 0110 0270 da08 7a05  .`.j.......p..z.
00000080: 08f0 b6fb 4800 0000                      ....H...

$ xxd -s 8200 -l 56 ring
00002008: ffff ffff 0000 0000 0000 0000 0000 0000  ................
00002018: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00002028: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00002038: 0000 0000 0000 0000                      ........
```

The first 4 bytes, `41 00 00 00`, are the record length, 65. The `08 72` after that is internal number 114. The 4-byte length field plus the 65 bytes of content make 69 bytes, and the next record starts 72 bytes later, at an 8-byte boundary. In the dump the remaining 3 bytes are 0, but the writing code does not zero this padding every time. The internal number is 114 and not 1 because the ring has already gone one lap and overwritten the start.

The second dump is the end of the data area. Writing 113 records of 72 bytes makes 8,136 bytes and leaves 56 bytes. A record does not fit, so the writing process writes `ff ff ff ff` in the length field to mark "skip from here to the end and go back to the start". The point is not to split a record across the end and the start.

If every record were 72 bytes, 14,563 of them would fit in the default size of 1MiB. If the total input is 15 trades per second, that is about 16 minutes' worth, and at 10,000 per second it is about 1.5 seconds' worth. Actual record sizes vary with the stock and the values, so this time is a calculation for gauging capacity.

### Write Order and Read Order

The problem is that overwriting. If the writing process goes one lap and overwrites a part while a reading process is copying a record, the copy mixes the old record and the new one. This is the "half-written value" I saw at the end of Part 2. To notice this, I put one more field in the header, `tail_intent`. Before writing bytes, the writing process first announces "I am about to overwrite up to here".[^7]

```rust
// 레코드 하나를 쓰는 세 단계. 건너뛰기 표시도 같은 순서를 지킨다.
fn put(&self, size: u64, len: u32, payload: &[u8]) {
    let tail = self.ring.tail().load(Relaxed);
    let end = tail + size;
    // 이전 쓰는 쪽이 tail_intent를 올리고 tail을 올리기 전에 죽었으면 tail_intent가 tail보다 앞서 있다. max는 그 값을 줄이지 않는다.
    self.ring.tail_intent().fetch_max(end, Relaxed);
    // Release 저장만으로는 뒤따르는 바이트 쓰기가 tail_intent보다 먼저 보일 수 있어서 fence를 둔다.
    fence(Release);
    let at = (tail % self.ring.capacity) as usize;
    let bytes = len.to_le_bytes().into_iter().chain(payload.iter().copied());
    for (slot, byte) in self.ring.data()[at..at + 4 + payload.len()].iter().zip(bytes) {
        slot.store(byte, Relaxed);
    }
    self.ring.tail().store(end, Release);
}
```

The write order has three steps: raise `tail_intent`, write the bytes, raise `tail`. The reading process moves in the opposite direction. It reads `tail` to see whether there is a new record, copies the bytes, and finally reads `tail_intent`.[^8]

```rust
pub fn read(&mut self) -> Read {
    let capacity = self.ring.capacity;
    loop {
        // 읽기 전용 매핑이라 Acquire load 대신 Relaxed load와 fence(Acquire)를 쓴다. 쓰는 쪽의 tail 저장(Release)과 짝을 이룬다.
        let tail = self.ring.tail().load(Relaxed);
        fence(Acquire);
        if self.pos == tail {
            return Read::Empty;
        }
        let at = (self.pos % capacity) as usize;
        let data = self.ring.data();
        let mut len = [0; 4];
        load(&data[at..at + 4], &mut len);
        let len = u32::from_le_bytes(len);
        let payload = if len == SKIP {
            None
        } else if len as usize > MAX_PAYLOAD || at + 4 + len as usize > capacity as usize {
            // 쓰는 쪽은 이런 len을 쓰지 않으므로 덮어쓰인 자리다. payload를 읽으면 영역 밖으로 나간다.
            return self.lost();
        } else {
            let mut payload = vec![0; len as usize];
            load(&data[at + 4..at + 4 + payload.len()], &mut payload);
            Some(payload)
        };
        // 쓰는 쪽의 fence(Release)와 짝을 이룬다. 복사한 바이트 중 하나라도 새로 덮어쓴 값이면, 쓰는 쪽이 그 전에 올린 tail_intent가 아래 load에 보인다.
        fence(Acquire);
        if self.ring.tail_intent().load(Relaxed) - self.pos > capacity {
            return self.lost();
        }
        match payload {
            None => self.pos += capacity - at as u64,
            Some(payload) => {
                self.pos += record_size(payload.len());
                return Read::Record(payload);
            }
        }
    }
}
```

The key is the check after the copy is done. If `tail_intent` is ahead of the reader's own position by more than one lap (`capacity`), that part may have been overwritten during the copy, so the copy is discarded.

<LiveDemo src="/demos/websocket-trade-server-rust-implementation/index.html?view=intent&lang=en" title="The order in which tail_intent reveals a record that was overwritten during copying" height={511} />

A reading process that discarded its copy moves its position to the current `tail` and logs the loss. Trades still remaining in the ring are skipped along with it. Instead of finding the start of the remaining records and recovering, I chose the simple policy of reading from the next write to complete. This loss is not announced to the client with a separate frame. The connection is not cut either, so the client cannot know that trades are missing. This problem comes up again when I cover the per-connection queue policy.

I made it actually happen. I had it write 50 trades per second into an 8,192-byte ring and stopped the `gateway` with `SIGSTOP` for 4 seconds, then resumed it.[^9] The ring holds 113 trades, so in 4 seconds it is overwritten nearly twice. This is the log from the `gateway` after it woke up.

```text
링에서 뒤처져 덮어쓰인 체결을 건너뛰었다
유실 225건: seq 172 다음에 398
```

The first line (it reads "skipped trades that were overwritten after falling behind on the ring") is the log that it detected falling behind on the ring. The second line (it reads "225 lost: 398 after seq 172") counted the 225 trades between the last internal number read, 172, and the next number, 398. It does not mean the bytes of all 225 trades were overwritten. It is the number of trades this `gateway` did not read, including the trades skipped when it moved to the current `tail`.

The approach of announcing intent with `tail_intent` before writing was modeled on Agrona's broadcast buffer. Agrona is also used in Aeron, the messaging library.[^10]

## Conditions the Ring Buffer Must Keep

At first I thought it would be enough to record the position before and after writing and check after copying. But in memory accessed concurrently, the order written in the code and the order observed on another core can differ. The code above only holds when read permissions, restarts, and length checks are also considered.

### Stores Do Not Become Visible in the Order They Were Made

First, the write order. Even if the `tail_intent` store is written before the byte writes in the code, there is no guarantee that another core observes it in the same order. Both compiler optimization and the CPU's memory ordering are involved. In JavaScript too, when Workers share a `SharedArrayBuffer`, you hit the problem of having to synchronize with `Atomics`.

A `Release` store alone is not enough. A read synchronized properly with this store can observe the work that came before the store, but here I need a relation with the byte writes that come after it. So I put a `fence(Release)` after raising `tail_intent`, and the reading process executes `fence(Acquire)` after copying the bytes.

What connects the two fences is the atomic reads and writes of the data area. If the reading process read even one newly overwritten byte, the Release fence before the write and the Acquire fence after the read synchronize. When it then reads `tail_intent`, it sees at least the position that write announced in advance, so it can discard the copy.[^11] Agrona also puts a release fence after storing the intent.

### Some Operations Work on Read-Only Memory and Some Do Not

The `gateway` maps the ring read-only. The aim is to keep wrong code from modifying the shared region. The Rust documentation places limits on atomic operations on read-only memory. For atomic values of 8 bytes or less on aarch64 and x86_64, which this implementation uses, `Relaxed` reads are guaranteed, but `Acquire` reads do not have the same guarantee.[^12] So I made every read `Relaxed` and get the needed ordering guarantee from `fence(Acquire)`.

### A Process That Died and Came Back Reduces the Value

The writing process may also die after raising only `tail_intent`. The process that comes back up continues writing from the existing file's `tail`, and if its first record is smaller than the one before the crash, the new position becomes smaller than the existing `tail_intent`. If that were stored as is, it would overlap the previous write, and a process in the middle of copying could miss the overwrite. `fetch_max` keeps the larger of the existing value and the new value and prevents this regression. The earlier `kill -9` experiment has no guarantee that the kill landed in this window, so I created this state separately in a test. I rewrite only the `tail_intent` in the ring file to 4,000 bytes ahead of `tail`, reopen the writing process, have it write a record, and check that `tail_intent` did not shrink.[^13]

### Trusting an Overwritten Length Reads Outside the Region

The first 4 bytes of a record can also be in the middle of being overwritten. If I trust them as a length and start copying, I may allocate memory with a wrong length or try to access outside the ring. The overwrite check comes after the copy, so I have to block this before reaching that check. The code above does not copy and treats it as a loss if the length exceeds the maximum of 4,096 bytes or goes past the end of the ring. In the test I rewrote the length field of the next record to a value at or below the maximum that still goes past the end of the ring, and checked that the reading process returns a loss.[^14]

### Even a Value You Will Throw Away Must Not Be Read That Way

The problem I found least intuitive was that discarding the copied value does not make the invalid access go away. At first I planned to read with a plain memory copy and discard the result if an overwrite was confirmed. I moved this approach into a small piece of code. One thread keeps overwriting 64 bytes, and another thread copies the same region and discards the result. It is complete code that runs if you put it as is into the `src/lib.rs` of a new crate.

```rust
#[cfg(test)]
mod tests {
    // 원시 포인터를 다른 스레드로 넘기려고 감싼다.
    struct Shared(*mut u8);
    unsafe impl Send for Shared {}

    #[test]
    fn copy_then_discard() {
        let bytes = Box::leak(Box::new([0u8; 64])).as_mut_ptr();
        let (for_writer, for_reader) = (Shared(bytes), Shared(bytes));
        let writer = std::thread::spawn(move || {
            let for_writer = for_writer;
            for round in 0..100u8 {
                for offset in 0..64 {
                    unsafe { for_writer.0.add(offset).write(round) };
                }
            }
        });
        let reader = std::thread::spawn(move || {
            let for_reader = for_reader;
            let mut copy = [0u8; 64];
            for _ in 0..100 {
                unsafe { std::ptr::copy_nonoverlapping(for_reader.0, copy.as_mut_ptr(), 64) };
            }
            // 복사본은 검사 뒤에 버릴 생각이었다.
            drop(copy);
        });
        writer.join().unwrap();
        reader.join().unwrap();
    }
}
```

This code passed in a normal test but failed under Miri. Miri is a tool that interprets Rust code and checks for undefined behavior such as data races.

```text
$ cargo test
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

$ cargo +nightly miri test
error: Undefined Behavior: Data race detected between (1) non-atomic write on thread `unnamed-2` and (2) non-atomic read on thread `unnamed-3` at alloc40314
  --> src/lib.rs:23:26
   |
23 |                 unsafe { std::ptr::copy_nonoverlapping(for_reader.0, copy.as_mut_ptr(), 64) };
   |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (2) just happened here
```

In Rust, one thread reading memory in a non-atomic way while another thread is writing it is itself undefined behavior. It does not matter whether the value read is used or discarded. The compiler optimizes the code on the assumption that this never happens, so there is no guarantee that the result stops at a mixed value. So I treated the whole data area as an array of atomic bytes (`&[AtomicU8]`) and made reads and writes atomic one byte at a time. The `slot.store(byte, Relaxed)` in `put` and the `load` that `read` calls are the result.

In Part 2, writing a 63-byte record to the ring with no reading process took 30ns. That value excludes the reading process's copy cost and the cost of several processes accessing at the same time. While the ring is empty it checks again at the default 200-microsecond interval, so this 30ns alone cannot explain the delivery latency either.

### What the Checking Tool Catches and What It Misses

I also checked the fixed code with Miri. Miri does not support file `mmap`, so I set up separate tests that run the same read and write code on heap memory. Four tests passed, including one where 2 threads exchange 2,000 records while one thread keeps overwriting.

I checked how far Miri catches things by deliberately breaking the code. It caught the non-atomic copy I showed earlier right away. For fences the result split in two. The code has three fences. One is in `read` right after it reads `tail`, and the other two, related to `tail_intent`, are the `fence(Release)` in `put` and the `fence(Acquire)` after the copy in `read`. Deleting all three makes the overwrite test fail with "레코드가 너무 짧다: 0바이트" (the record is too short: 0 bytes). This is because Miri also emulates a `Relaxed` read returning an old value: without the fence right after reading `tail`, the reader can see the new `tail` and still read that record's bytes as they were before the write. On the other hand, the code where I kept that fence and deleted only the two related to `tail_intent` passed all four tests. So even when a fence needed to notice an overwrite is missing, this test does not tell me. That means I cannot judge from this run alone that the ordering guarantees are sufficient. The relation between atomic operations and fences has to be worked out separately. The case where different processes map the file is also outside the checking range of this heap test. In a real mapping it depends on the premises that the operating system shares the same page and that the target CPU's atomic operations and memory ordering guarantees apply across processes as well.

## From the Ring to the Async Runtime

In the `gateway`, what reads the ring is not a task of the async runtime but a dedicated thread.[^15]

```rust
thread::spawn(move || {
    let mut reader = open(&path);
    let mut last_seq = None;
    loop {
        match reader.read() {
            Read::Empty => thread::sleep(poll),
            Read::Lost => eprintln!("링에서 뒤처져 덮어쓰인 체결을 건너뛰었다"),
            Read::Record(payload) => {
                let Ok(trade) = Trade::decode(payload.as_slice()) else {
                    eprintln!("Trade로 디코딩하지 못한 레코드를 버렸다");
                    continue;
                };
                if let Some(last) = last_seq {
                    report_gap(last, trade.seq);
                }
                last_seq = Some(trade.seq);
                match trade::to_message(&trade) {
                    Some((topic, body)) => hub.publish_blocking(topic, body),
                    None => eprintln!("본문을 만들 수 없는 체결을 버렸다: seq {}", trade.seq),
                }
            }
        }
    }
});
```

I did not attach any mechanism to this ring that signals that new data has arrived. Unlike a socket, there is no runtime notification to wait on, so it checks the read position directly, and when it is empty it rests for the default 200 microseconds with `thread::sleep`. This call blocks the thread, so it runs outside the tokio workers. An implementation that polls with an async timer is also possible, but here I gathered polling and decoding into one dedicated thread.

If the polling interval is long, it can take longer to discover a trade. Conversely, if it checks without resting, it keeps using the CPU. Latency and CPU usage as a function of the interval are compared in Part 4.

The JSON body is built once per trade on this thread. Even if 10,000 connections subscribe to that stock, the body is not built 10,000 times. The built body is held in an `Arc<str>`. `Arc` is a reference counter that lets many places point to the same data, and copying it does not copy the characters, it only adds 1 to the counter.

## The Subscription Index

The subscription index is used to find the connections to send a trade to. It manages per-connection state and per-topic subscription lists as two tables.[^16]

```rust
#[derive(Default)]
struct State {
    clients: HashMap<u64, Client>,
    index: HashMap<String, Vec<(u64, Arc<str>)>>,
}
```

`index` keeps pairs of connection number and subscription id for each topic. If the same connection subscribes to one stock twice, there are two entries. When publishing, it walks this list and sends the trade to each subscription, and the subscription id goes into the `subscription` header of the `MESSAGE`.

When subscribe and unsubscribe requests come in, the tables must be modified, and when a trade comes in, the subscription list must be read. If the task running for each connection accessed the tables directly, synchronization would be needed. Here a single task owns the tables, and the connection tasks and the thread reading the ring only send it the following commands.[^17]

```rust
enum Command {
    Connect { conn: u64, queue: mpsc::Sender<Outgoing>, kick: oneshot::Sender<()> },
    Subscribe { conn: u64, id: String, destination: String, receipt: Option<String> },
    Unsubscribe { conn: u64, id: String, receipt: Option<String> },
    Disconnect { conn: u64 },
    Publish { topic: String, body: Arc<str> },
}
```

<LiveDemo src="/demos/websocket-trade-server-rust-implementation/index.html?view=hub&lang=en" title="Connection tasks and the thread reading the ring only send commands, and a single hub task modifies the index" height={416} />

The hub task takes commands from the channel one at a time and handles them. No other task can modify the tables directly, so the tables themselves need no locks. State changes are gathered in one place, and the synchronization cost of the channel that carries the commands remains.

### The Order of the Subscription Confirmation and the First Trade

In Part 2, the subscription confirmation (`RECEIPT`) arrived before the first `MESSAGE` of that subscription. To keep this order, the subscription registration and the confirmation response are handled within the same command.[^18]

```rust
fn subscribe(&mut self, conn: u64, id: String, destination: String, receipt: Option<String>) {
    let Some(client) = self.clients.get_mut(&conn) else {
        return;
    };
    let id: Arc<str> = id.into();
    if let Some(old) = client.subs.insert(id.clone(), destination.clone()) {
        self.unindex(conn, &id, &old);
    }
    self.index.entry(destination).or_default().push((conn, id));
    // 색인에 올린 바로 이 자리에서 RECEIPT를 큐에 넣는다. 이후 발행분은 항상 그 뒤에 쌓인다.
    if let Some(receipt) = receipt {
        self.deliver(conn, Outgoing::Receipt { receipt_id: receipt, message: "subscribe success" });
    }
}
```

Right after putting the new subscription in the index, within the same command, the `RECEIPT` goes into the connection's queue. A publish command cannot get in between, so later trades pile up behind the confirmation. When unsubscribing, the entry is removed from the index first and then the confirmation response is put in. Trades that were already in the queue are ahead of the response, and later publishes do not go to the unsubscribed subscription. This order is kept by using serial command processing together with the per-connection FIFO queue.

### How Long a Single Hub Takes

A single hub handles every trade in turn, so while it is distributing one trade into queues, the next trade and subscription requests both wait. I measured how long this section takes by isolating the hub.[^19] I had N connections subscribe to the same topic, published one trade to that topic, and right after that published one more trade to another topic with only one subscriber. The hub handles commands in order, so by the time the second trade arrives, the first has been put into all N queues. I measured the time from the publish to that moment 200 times and took the median, and repeated the same measurement three times.

I varied two conditions. One is the gap between publishes. I measured publishing back to back without resting, and publishing after resting 67ms, the average gap at 15 trades per second. The other is the task receiving from the queue. I measured holding only the queues, and also spawning a task per queue waiting in `recv`, like the connection tasks of the real server. When there are waiting tasks, the hub wakes that task every time it puts something in a queue. These tasks just discard what they receive and do not write to a socket.

| Subscribed connections | Back-to-back publishes, queues only | Back-to-back publishes, waiting tasks | 67ms gap, queues only | 67ms gap, waiting tasks |
| ---------------------- | ----------------------------------- | ------------------------------------- | --------------------- | ----------------------- |
| 100                    | 0.01ms                              | 0.03ms                                | 0.10ms                | 0.14ms                  |
| 1,000                  | 0.02ms                              | 0.17ms                                | 0.48ms                | 0.99ms                  |
| 10,000                 | 0.30ms                              | 1.48ms                                | 4.47ms                | 8.69ms                  |

The values in the table are the middle value of the three runs. The three runs for the 10,000-connection row, from the leftmost column, were 0.29ms to 0.30ms, 1.47ms to 1.53ms, 4.46ms to 4.63ms, and 8.68ms to 8.83ms.

Looking only at the leftmost column of the 10,000-connection row, putting into one queue takes 30ns. But this value is the lower bound when the hub repeats the same work without a moment's rest. It takes 5 times as long once the hub also wakes the waiting tasks, 15 times as long when it rests 67ms before publishing, and 29 times as long with both conditions together. The condition closest to the 15 per second I use as the base load in Part 4 is the rightmost column. On this Mac, when 10,000 connections subscribe to one stock, the time for the hub to distribute one trade is closer to 9ms than to 0.3ms.

To narrow down why it gets slower when it rests before publishing, I ran tokio on a single thread (`current_thread`) and had it wait the 67ms in a busy loop instead of sleeping. With 10,000 connections and only queues, it was 4.3ms to 4.4ms in all three runs when it slept, and 0.63ms to 0.64ms in all three runs when it waited in a busy loop. The cause of the slowdown is the thread having gone to sleep and woken up, not the elapsed time. My guess is that the core's cache or clock state changes while the thread sleeps, but I did not confirm that.

None of the columns includes the cost of writing to a socket. So I do not put this value side by side with the TCP `send` of 1,915ns from Part 2. The latency of the whole server, including the connection tasks writing to sockets, is measured in Part 4.

What happens if input is faster than the hub can process? The hub receives commands through a channel of 1,024 slots. The ring-reading thread's `publish_blocking` waits until a slot opens when this channel is full.[^20] Meanwhile the `feed` keeps writing, so trades that fall behind can be overwritten in the ring. Subscribe and unsubscribe use the same channel, so when publishing backs up, these requests are delayed too.

## Per-Connection Queues and a Client That Does Not Read

When a trade arrives, the hub walks the subscription list and puts the message into the queue, one per connection.[^21]

```rust
fn publish(&mut self, topic: &str, body: Arc<str>) {
    let Some(targets) = self.index.get(topic) else {
        return;
    };
    let mut full = Vec::new();
    for (conn, id) in targets {
        let Some(client) = self.clients.get(conn) else {
            continue;
        };
        let message = Outgoing::Message { subscription: id.clone(), body: body.clone() };
        if let Err(TrySendError::Full(_)) = client.queue.try_send(message) {
            full.push(*conn);
        }
    }
    for conn in full {
        self.drop_slow(conn);
    }
}
```

`try_send` fails without waiting if the queue has no free slot. If the hub waited until a slow connection's queue emptied, publishing to the other connections would stop too, so when it finds a full queue it removes that connection.

<LiveDemo src="/demos/websocket-trade-server-rust-implementation/index.html?view=slow&lang=en" title="Only the connection whose queue is full is disconnected, and publishing to the other connections continues" height={528} />

The per-connection queue has 1,024 slots. Trades pile up within that limit, and when no more fit, the connection is disconnected. Unlike items such as cumulative volume, where the next frame carries an updated value, in a trade list each frame is one row. If an intermediate trade is silently dropped, that row is missing. The `message-id` is also attached after taking the message out of the queue, so the fact that a trade was dropped does not show up in the numbers.

Disconnecting at least lets the client know that normal reception has stopped. But reconnecting does not bring back the missing trades. This version has no resending of past trades or re-querying of the list, so a client must not treat the list before and after a reconnect as a complete record.

I did not keep this standard across the whole server. Trades the `gateway` skipped after falling behind on the ring go missing while the connection stays up, and when the `feed` comes back up, the cumulative values return to 0, and no sign of it goes to the client. A single connection that does not read is told by being disconnected, while trades that every connection loses together go unannounced. The `gateway` knows there was a loss from `Read::Lost` and the jump in the internal number, but it does not know which stock the unread records belonged to. So to announce it, it would have to tell every connection, and the server in this post only leaves a log, and the later repository stopped at counting the occurrences.[^22] For a screen where the trade list must have no gaps, announcing the loss at this stage matters more than disconnecting a connection whose queue is full.

Some screens are better off dropping. For a screen that shows only the current price, sending the most recent trade is better than sending the backed-up trades in order. The server in this post has no such mechanism, and the later repository added a latest-first policy that applies only to selected topics. A subscription that has 64 (the default) or more backed up in the queue keeps only the most recent trade in one slot and skips the trades before it. Personal topics do not use this policy even if they are put in the list. This is because events that cannot be replaced by a later event, such as order creation, would disappear.[^23] What the disconnect policy produces under overload is covered in Part 4.

### How Long Until the Disconnect

I made 1 of 10 connections subscribe but not read, and checked when it was cut off.[^24] I ran it three times with a load that sends about 920 frames per second per connection, and the following log appeared 2.70 seconds, 2.73 seconds, and 2.79 seconds after trades started being written.

```text
느린 클라이언트 차단: conn 2
```

(It reads "slow client blocked: conn 2".) These 2.7 seconds split into two phases. During the run I read the amount piled up in kernel buffers with `netstat` every 20ms. The sum of the `gateway`'s send buffer and the client's receive buffer grew until 1.6 seconds and then stopped at about 558 thousand bytes. When the kernel accepts no more, the write task's `send` does not finish, and from then on trades pile up in the per-connection queue. At 920 per second, the 1,024 queue slots fill in 1.1 seconds. The time from the buffer stopping to the disconnect was also 1.1 to 1.2 seconds in all three runs.

| Run | Frames per second | Time the buffer stopped | Size at stop  | Time disconnected | Time from stop to disconnect | Time to fill 1,024 queue slots |
| --- | ----------------- | ----------------------- | ------------- | ----------------- | ---------------------------- | ------------------------------ |
| 1   | 935               | 1.58s                   | 558,072 bytes | 2.70s             | 1.13s                        | 1.10s                          |
| 2   | 930               | 1.61s                   | 557,637 bytes | 2.73s             | 1.13s                        | 1.10s                          |
| 3   | 914               | 1.59s                   | 557,857 bytes | 2.79s             | 1.20s                        | 1.12s                          |

The other 9 connections were not disconnected in any of the three runs, and received every trade written during the measurement window without missing one. In the second run, all 66,933 frames the 9 connections should have received arrived. Whether the latency of the other connections changes when I raise the connections that do not read to 10 is checked in Part 4.

For a stock with infrequent trades, the same process stretches out much longer. I subscribed to one stock with an average of 15 trades per second and created a connection that does not read.[^25] The kernel buffer, checked with `netstat` every 5 seconds, grew until about 110 seconds and then stopped growing at 596,214 bytes, and the connection was disconnected 181 seconds after the `gateway` started reading trades. At 14.9 per second, filling the 1,024 queue slots takes 69 seconds, so adding that to the 110 seconds when the buffer stopped gives 179 seconds. Just before the disconnect, about 600 thousand bytes of kernel buffer and a queue of 1,024 trades had piled up.

When no trades come in, the condition of the queue filling and disconnecting also does not occur. The heartbeat does not pass through the queue, and the write task sends it on a timer. This version does not check whether the peer's heartbeat has stopped, and it also puts no deadline on socket writes. So an empty queue alone does not let me conclude that the peer is reading normally. The later repository added a `--write-timeout-ms` option that sets a deadline for a single write. It is off by default, and when turned on, it closes the connection if a write does not finish within the deadline.[^26]

### Where the Sequence Number Is Assigned

What takes a message out of the queue and builds the frame is each connection's task.[^27]

```rust
// message-id의 seq는 이 연결로 실제 나가는 순서대로 여기서만 매긴다.
let mut seq: u64 = 0;
loop {
    let text = tokio::select! {
        outgoing = outgoing.recv() => match outgoing {
            Some(Outgoing::Receipt { receipt_id, message }) => stomp::receipt(&receipt_id, message),
            Some(Outgoing::Message { subscription, body }) => {
                seq += 1;
                stomp::message(&format!("{connection_id}-{seq}"), &subscription, &body)
            }
            None => return,
        },
        _ = beat.tick() => "\n".to_string(),
    };
    if writer.send(Message::text(text)).await.is_err() {
        return;
    }
}
```

`tokio::select!` waits on several async operations and handles the one that becomes ready. Here it waits for either a message from the queue or the timer to fire. When a message arrives it builds a frame, and when the timer is chosen it sends a newline as the heartbeat. The next iteration begins only after `writer.send` finishes, so while the socket write is blocked, the heartbeat waits along with it.

The `message-id` is incremented in one place, the connection's write loop. One number is attached to each `MESSAGE` taken from the queue, matching the order in which frames are attempted to be sent. The `send` after that can fail, so having attached a number does not guarantee delivery. Assigning per-connection numbers in the hub could also preserve FIFO order, but here I gathered frame assembly and number management in the write task. Trades skipped on the ring never reach this loop, so no gap appears in the numbers.

The JSON body held in an `Arc<str>` is shared between the hub and the per-connection queues. Instead of copying the whole body for every queue, it clones the reference, and when assembling the frame it joins the header and body into one string. In this implementation the body is copied per connection at that point. A design that shares the body as a separate buffer even when the headers differ is possible, but here I assembled it into one string and passed it to the existing WebSocket API.

## Comparing With the Captured Frames

The frame the server built this way sends out is as follows. The values are arbitrary ones the `feed` made up.

```text
MESSAGE
message-id:00000000-0000-4000-8000-000000000000-1
subscription:0
content-length:248
content-type:application/json

{"code":"A005930","dt":"2026-11-19T16:07:36Z","currency":"KRW","exchange":"krx","session":"REGULAR","base":70000,"close":69900,"volume":9,"tradeType":"SELL","changeType":"DOWN","tradingStrength":90.43,"cumulativeVolume":9,"cumulativeAmount":629100}^@
```

To compare this frame with the real capture, I extracted the header order, the keys and data types of the body, and the order in which responses come. I ran the same extractor on a capture of my own server and compared the results.

<LiveDemo src="/demos/websocket-trade-server-rust-implementation/index.html?view=contract&lang=en" title="Comparing the frame shapes of the real capture and my own server with the same extractor" height={569} />

The extractor removes or replaces authentication headers and device identifiers, and for market data it picks out things like data types and digit counts. The output also contains the 56 frames the client sent (1 connect, 31 subscribe, 17 unsubscribe, 7 heartbeat) and their send times. The replay client schedules the same subscriptions and unsubscriptions based on these times. The actual intervals may differ slightly depending on timers and the execution environment. It is a scenario of about 37 seconds, with subscribes and unsubscribes mixed, from a capture made by opening and closing two tabs.

Of 74 items, 59 were the same and 15 differed. The 15 that differed fall into the following four kinds.

| Item that differs                     | Real capture                                           | My own server             | Why it differs                   |
| ------------------------------------- | ------------------------------------------------------ | ------------------------- | -------------------------------- |
| Compression negotiation               | `permessage-deflate`                                   | None                      | I did not implement compression  |
| Counts and messages per second        | Domestic 1,211, US 26                                  | Domestic 1,743, US 453    | The trades are made up           |
| Digit counts and vocabulary of values | Trading strength of 19 digits, only `UP` for US stocks | 5 digits, `UP` and `DOWN` | The trades are made up           |
| Times                                 | Heartbeat interval 4,879ms to 5,123ms                  | 4,999ms to 5,001ms        | It differs with each measurement |

In this replay, the header names and order, the body keys and order, the data types, and the `message-id` format and continuity were the same. The order in which the subscription confirmation comes before the first trade and no trade of that subscription comes after the unsubscribe confirmation, and the NUL-terminated format, also matched. But since there are differences starting with compression negotiation and the digit counts of values, I cannot say that the two servers are indistinguishable. What I confirmed is whether the items the extractor checked in this scenario matched.

This comparison does not tell me the internal structure of the original server. Whether it uses shared memory, how many processes it has, and what its overload policy is are separate questions. All I confirmed is that the structure I built here can reproduce part of the observed frame format and the order of subscription handling.

## The Scope You Drop When You Fall Behind

The `feed` overwrites the ring without waiting for reading processes. The thread reading the ring waits when the hub's command channel is full. The hub removes a connection when its per-connection queue is full. Even within the same server, the way backed-up data is handled differs from one stage to the next. Of these, the only one the client can know about is the last case, where the connection is disconnected.

With this structure, I could keep the existing WebSocket connections up even when I started the `feed` again, and I could cut off one connection that does not read, separate from the rest. In exchange, when the ring falls behind, trades are skipped and the client is not told, and reconnecting does not recover the missing trades. Keeping the connection up alone could not guarantee the completeness of the trade list. In the next post I raise the connections to 10,000 and look at where things start to back up and how much a slow connection affects the latency of the other connections.

[^1]: You can rerun it in the following order. Start `feed --rate 20` and the `gateway`, and subscribe to Samsung Electronics trades with [yceffort/ws-trade-server `ad576ce` `examples/watch-seq.js`](https://github.com/yceffort/ws-trade-server/blob/ad576ce552d30f01f7b44f6f737cb8c997552a0b/examples/watch-seq.js). After 4.5 seconds, kill the `feed` with `kill -9`, and 3 seconds later start it again with the same command.

[^2]: [yceffort/ws-trade-server `86ffa4d` `examples/trade_bytes.rs`](https://github.com/yceffort/ws-trade-server/blob/86ffa4de453a102dc84e1a46d90188c8a8da1124/examples/trade_bytes.rs). This example was added after the pinned commit, and it compiles as is if put into the pinned commit. The trade values are made with random numbers, so the sizes differ a little on each run. When I ran it three more times, the protobuf was 62 to 64 bytes and the JSON body was 249 to 250 bytes.

[^3]: [Protocol Buffers encoding documentation](https://protobuf.dev/programming-guides/encoding/). A tag is `(field_number << 3) | wire_type` encoded as a variable-length integer.

[^4]: [yceffort/ws-trade-server `47563840` `proto/feed.proto` L39-L44](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/proto/feed.proto#L39-L44)

[^5]: [yceffort/ws-trade-server `47563840` `src/trade.rs` L125-L139](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/src/trade.rs#L125-L139)

[^6]: Start `feed --ring ring --capacity 8192 --symbols kr:A005930 --rate 50`, stop it after 2.6 seconds, and read the file, and you get the same shape. At 50 per second it writes slightly more than one lap (113 records) in that time. The values differ on each run.

[^7]: [yceffort/ws-trade-server `47563840` `src/ring.rs` L113-L127](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/src/ring.rs#L113-L127)

[^8]: [yceffort/ws-trade-server `47563840` `src/ring.rs` L148-L185](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/src/ring.rs#L148-L185)

[^9]: Add `gateway --ring ring` to the same `feed` command as the earlier dump, and send `kill -STOP` to the `gateway`, then `kill -CONT` 4 seconds later.

[^10]: [aeron-io/agrona `2.2.4` `BroadcastTransmitter.java` L129-L133](https://github.com/aeron-io/agrona/blob/6cccef42c620a117da1fa0a8d2d6fb80a163821e/agrona/src/main/java/org/agrona/concurrent/broadcast/BroadcastTransmitter.java#L129-L133). `signalTailIntent` stores the value and then calls `VarHandle.releaseFence()`.

[^11]: [Rust 1.95.0 standard library, the Fence-fence section of std::sync::atomic::fence](https://doc.rust-lang.org/1.95.0/std/sync/atomic/fn.fence.html#fence---fence). When an atomic read before an Acquire fence observes an atomic write after a Release fence, the two fences synchronize.

[^12]: [Rust 1.95.0 standard library, the Atomic accesses to read-only memory section of std::sync::atomic](https://doc.rust-lang.org/1.95.0/std/sync/atomic/index.html#atomic-accesses-to-read-only-memory)

[^13]: [yceffort/ws-trade-server `47563840` `tests/ring.rs` L118-L133](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/tests/ring.rs#L118-L133)

[^14]: [yceffort/ws-trade-server `47563840` `tests/ring.rs` L77-L90](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/tests/ring.rs#L77-L90)

[^15]: [yceffort/ws-trade-server `47563840` `src/bridge.rs` L13-L36](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/src/bridge.rs#L13-L36)

[^16]: [yceffort/ws-trade-server `47563840` `src/hub.rs` L31-L35](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/src/hub.rs#L31-L35)

[^17]: [yceffort/ws-trade-server `47563840` `src/hub.rs` L11-L17](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/src/hub.rs#L11-L17)

[^18]: [yceffort/ws-trade-server `47563840` `src/hub.rs` L94-L107](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/src/hub.rs#L94-L107)

[^19]: I ran [yceffort/ws-trade-server `7e56252` `examples/hub_fanout.rs`](https://github.com/yceffort/ws-trade-server/blob/7e56252350941587c55eea5848f571d19ceaae72/examples/hub_fanout.rs) with `cargo run --release --example hub_fanout -- 0` and `-- 67000`. The argument is the rest time between publishes (in microseconds). I did the comparison of sleeping and the busy loop with [`examples/hub_idle.rs`](https://github.com/yceffort/ws-trade-server/blob/7e56252350941587c55eea5848f571d19ceaae72/examples/hub_idle.rs). Both examples were added after the pinned commit, and they compile as is if put into the pinned commit. I measured on December 3, 2026.

[^20]: [yceffort/ws-trade-server `47563840` `src/hub.rs` L82-L85](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/src/hub.rs#L82-L85). The channel size of 1,024 is set at L39 of the same file.

[^21]: [yceffort/ws-trade-server `47563840` `src/hub.rs` L122-L139](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/src/hub.rs#L122-L139)

[^22]: [yceffort/ws-trade-server `ea6d424` `src/bridge.rs` L67-L70](https://github.com/yceffort/ws-trade-server/blob/ea6d424b8a6f0fb90b7b35f12b65418cc811c9a9/src/bridge.rs#L67-L70). It raises the `ring_overruns` counter and moves on.

[^23]: [yceffort/ws-trade-server `ea6d424` `src/hub/state.rs` L89-L105](https://github.com/yceffort/ws-trade-server/blob/ea6d424b8a6f0fb90b7b35f12b65418cc811c9a9/src/hub/state.rs#L89-L105). The reason for excluding personal topics is in the comment at [`src/hub.rs` L162-L164](https://github.com/yceffort/ws-trade-server/blob/ea6d424b8a6f0fb90b7b35f12b65418cc811c9a9/src/hub.rs#L162-L164) of the same commit. It is off by default, so if you do not turn it on, a connection whose queue is full is disconnected, as in the server in this post.

[^24]: I started the `gateway` of the pinned commit `47563840` with default settings and ran `loadgen --connections 10 --stalled 1 --probes 9 --rate 304 --warmup 1 --seconds 8`. `loadgen` writes the trades of 3 stocks directly into the ring, and times were measured from when `loadgen` started writing. The kernel buffer is the sum of Recv-Q and Send-Q shown by `netstat -an -p tcp`, added over all sockets using that port. I measured on December 3, 2026.

[^25]: I started the `gateway` of the pinned commit `47563840` with default settings and ran `loadgen --connections 2 --stalled 1 --probes 1 --symbols kr:A005930 --rate 15 --warmup 1 --seconds 260`. It is 1 connection that does not read and 1 connection that counts the trades it receives. The connection that counts the received trades received all 3,869 trades during the 260-second measurement window without missing one. I measured on the same Apple M5 Mac on November 25, 2026.

[^26]: [yceffort/ws-trade-server `ea6d424` `src/connection/write.rs` L66-L72](https://github.com/yceffort/ws-trade-server/blob/ea6d424b8a6f0fb90b7b35f12b65418cc811c9a9/src/connection/write.rs#L66-L72)

[^27]: [yceffort/ws-trade-server `47563840` `src/connection.rs` L125-L142](https://github.com/yceffort/ws-trade-server/blob/47563840775daf4ac94ab106452730e7beac9a28/src/connection.rs#L125-L142)
