High-Speed Data Streams and Efficient Concurrency: Reduce Accumulated Waits with Rust and Tokio

Price updates are reaching your trading application, but they take time to affect its decisions. As the number of updates rises, the application's state falls further behind the market. This symptom calls for examining both how you obtain the data and the processing path after it arrives.
Receiving updates, extracting data, updating state, checking conditions, and saving records. When several stages wait for the previous operation to finish before proceeding, it takes longer for the data to reach the decision logic. If subsequent updates keep arriving in the meantime, those waits accumulate further. To turn a fast stream into a responsive application, separate work that can progress independently while preserving the order that is required.
This article is for developers implementing price reception and decision logic in TypeScript, Python, or similar languages. We follow an update from a price feed as your application receives it, applies it to state, checks conditions, and retains the result as an auxiliary record. The destination is an application-side file or database; the runnable examples here use files.
Using auxiliary saving as the example, this article translates the boundary between ordered processing and work that can progress separately into code. We first diagnose what your receive path is waiting for and make reasonable improvements to an existing TypeScript implementation. We then examine how Rust/Tokio, our first recommendation for a low-latency reception and decision engine, lets you control ownership, shared state, execution placement, and concurrency limits. This continues the separation of the hot path and auxiliary work from the previous article on low-latency architecture through implementation and verification.
The records saved here are auxiliary records that do not need to be durable before the next decision. This same substitution cannot remove a step that correctness depends on, such as persistence required before an order is sent. In an application where reception and saving are already separate, the problem may instead be a growing number of unfinished saves. Trace the callers to determine which case applies.
The goal is to learn the processing patterns that create waits and how to restructure them. You should be able to read the dependencies in your own code and decide which order must be preserved and which work can progress separately. A diagram using prices 100 → 101 explains the principle, and small runnable examples verify decision results, order, and record retention. This article does not report improvement percentages in a live environment or rank languages by speed.
Even if trading conditions are written correctly, you still need to investigate the waits before a new price reaches those conditions. Trace which operation must finish before the next decision can proceed, then choose which parts need to remain ordered and which can progress separately. This knowledge also lets you tell an AI exactly where to investigate and which conditions to preserve when requesting a fix, and assess whether its proposed change would actually help.
The main subject here is concurrency: progressing other work while waiting for input/output (I/O), such as files or network communication. We distinguish this from parallelism, where calculations execute simultaneously on multiple CPU cores. In either Rust or TypeScript, writing
async alone does not move heavy computation to another CPU.[S03][S07][S08][S13]Sections 1 and 2 connect symptoms to design. Sections 3 and 4 follow the same six prices in TypeScript and Rust. Sections 5 and 6 cover full queues, failures, and shutdown; Section 7 maps the design to real receive code; and Section 8 provides the execution steps. If you are starting by diagnosing existing TypeScript or Python code, you can read Sections 1–3 and then Sections 5–8, returning to Section 4 when considering a Rust implementation. If you want to begin with the principle, follow the progress of decisions and saving through the prose and diagrams in Sections 1, 2, 5, and 6.
Section 10 is an appendix to copy in full when working in your own repository. After understanding the causes and the conditions to preserve in the main article, use it to ask an AI agent to diagnose, modify, and verify your code.
Tap or click a diagram to open the image at its original size.
1. What Must Finish Before the Next Update Can Proceed?
Start with the condition that allows processing of the next update to begin. The following code applies the price and checks the trading conditions, then saves an auxiliary record.
typescript
for await (const update of updates) {
state.apply(update);
const decision = decide(state);
await saveAuxiliary({ seq: update.seq, price: state.price, decision });
}for await (const update of updates) {
state.apply(update);
const decision = decide(state);
await saveAuxiliary({ seq: update.seq, price: state.price, decision });
}While asynchronous I/O is pending, the Node.js event loop can progress other work. This loop, however, does not move to the next iteration until the save Promise resolves. Even if an update with price 101 arrives while the record for price 100 is being saved, this loop cannot use price 101 until that save finishes.[S12][S14]
Check the existing code and a small local replay to establish whether this dependency exists. Match the following timestamps for the same update ID.
| Timestamp | Where to instrument the code | What to check |
|---|---|---|
| Processing start | Immediately after taking an update | Whether the next update cannot be taken until the previous save finishes |
| Condition-check completion | Immediately after applying state and checking conditions | Whether state application and condition checking take a long time, or processing is held up before it starts |
| Save start and completion | Immediately before calling save and after it completes | Whether waiting for a save delays the start of subsequent processing |
For example, when replaying only a small fixed set of inputs, you can place measurement points as follows. This example shows where to measure.
finiteUpdates contains at most six inputs, and trace retains only those six inputs' measurements; display or file output happens after replay. If saving fails, do not record a completion time, and let the exception propagate to the existing failure handler.typescript
const trace = [];
for (const update of finiteUpdates) {
const started = performance.now();
state.apply(update);
const decision = decide(state);
const decided = performance.now();
const record = { seq: update.seq, price: state.price, decision };
const saveStarted = performance.now();
let saved: number | undefined;
try {
await saveAuxiliary(record);
saved = performance.now();
} finally {
trace.push({ seq: update.seq, started, decided, saveStarted, saved });
}
}const trace = [];
for (const update of finiteUpdates) {
const started = performance.now();
state.apply(update);
const decision = decide(state);
const decided = performance.now();
const record = { seq: update.seq, price: state.price, decision };
const saveStarted = performance.now();
let saved: number | undefined;
try {
await saveAuxiliary(record);
saved = performance.now();
} finally {
trace.push({ seq: update.seq, started, decided, saveStarted, saved });
}
}If processing of the next update starts after the previous save completes, and the call relationship shows the same dependency, you can confirm that processing waits for saving. That alone, however, does not establish that all the wait was caused by saving. The input itself may not yet have arrived, so also compare the scheduled arrival time or an available reception timestamp. In the small runnable examples here, the same six inputs are all ready at the start. They do not reproduce actual arrival intervals. When using real data, also record the captured input sequence and the boundary where measurement starts.
For a real stream, state whether “reception time” means receipt at the socket, the start of the SDK callback, or the point where the application takes the update. Do not subtract a server send timestamp from the local clock without checking the clock offset.
Where to Look in an SDK Callback
An SDK is a library that lets an application use capabilities such as receiving data. If you register a function called for each update—a callback—with the SDK, also record the update ID and timestamp at that entry point. Record
received at entry, and record the point when state.apply actually begins separately as started. If your own processing queue sits between them, an update may have reached the callback without state application having started.For example, consider a local replay of only two updates: leave the save for price 100 unfinished and deliver price 101 in the meantime. Match the following differences to the
started, decided, and saved timestamps above.| Observation | Decisions and saving in one loop | An async callback for each event |
|---|---|---|
| Price 101 is received before saving price 100 finishes | Reception is recorded, but state application for price 101 has not started | The callback for price 101 may be invoked, allowing state application and condition checking to progress |
| The condition check for price 101 begins | Saving price 100 has already finished | Saving price 100 may still be in progress |
| What to trace next | The queue between reception and decision processing, and the loop that waits for save completion | The number of overlapping saves, their completion order, and state updates before and after await |
Node.js
EventEmitter does not wait for the Promise returned by an async listener to complete before invoking the next event.[S21] To determine whether an SDK independently waits for Promises, compare its caller implementation with observations. Section 7 examines the actual invocation pattern in the Solana Stream SDK. If the decision for price 101 progresses before saving price 100 finishes, you cannot diagnose that path as one where saving blocks the next decision.In the latter case, unfinished saves overlap when new inputs keep arriving before previous saves finish. Saves may also complete out of order, so the design needs to control how many start and in what order. This article uses one writer and a bounded queue. The difference is also checked in an execution-order example using two fixed updates and simulated saves completed manually. This is a diagnostic for the condition that allows the next decision to start, not an elapsed-time comparison. It includes neither a real SDK connection nor a performance measurement of real I/O.
Check When Saving May Be Deferred
Saving is not the only source of waits. Measure each stage and choose a change that addresses the cause.
| Area to examine | Source of delay | Boundary to consider changing |
|---|---|---|
| Saving to a database or file | Time waiting for I/O to complete | Hand auxiliary saving that may finish after the next condition check to separate processing |
| JSON encoding, compression, and computation | Time occupying the CPU | Reduce the data passed along and, if necessary, move the work to execution resources for CPU work |
| Bounded queue | Time waiting for capacity | Check capacity, input volume, processing capacity, and the policy when full |
| Mutex and similar mechanisms | Time waiting for a lock to be released | Revisit who updates state, the scope of locking, and how long the lock is held |
State updates and the condition checks that use that state have an order. Independently parallelizing every stage is not sufficient. The dependency removed here is waiting for auxiliary saving that the next condition check does not require. A filename or the label “log” does not determine whether a record is auxiliary.
| Example of what is saved | What to check in your specification and code | Decision about separation |
|---|---|---|
| Price and decision history for observation | Can the next decision use in-memory state and tolerate delayed saving? Do other processing or recovery paths depend on this save completing? | If those conditions are confirmed, it is a candidate for the separation shown here |
| Records that prevent duplicate orders after a restart | Does the contract require successful persistence of an identifier before the order is sent? | If it is required, keep the wait for saving before sending the order |
| Balance caches or quote history | Is this display data that can be fetched again, or the basis for the next settlement, balance update, or recovery? | Decide after tracing consumers and recovery processing |
Even a record of the same price and decision result requires different handling depending on whether it is used only for observation or as a basis for recovery. Check where saved results are read, failure handling, restart handling, specifications, and existing tests. If the dependency is unclear, retain the wait for saving while investigating. This runnable example covers the calculation of trading conditions, not the preconditions for sending an order from a decision result.
2. Let the Same Work Progress Separately
Check trading conditions using price 101 while saving the record for price 100. Let us examine which wait is reduced when these two operations progress separately.
The decision rule is
enter when the previous price was below 101 and the current price is at least 101, exit for the reverse transition, and hold otherwise and for the first update. Because the rule needs the previous state, it also demonstrates why update order matters. This is a simple condition check for comparing designs; it sends no orders.Figure 1 illustrates a loop that waits for save completion. It is an explanatory model in which price 100 arrives at 0 ms, price 101 at 10 ms, condition checking takes 1 ms, and saving each record takes 30 ms. Input time and processing-start time are distinct, and both approaches receive the same updates. The times in the diagram are assumptions, not measurements.
Before the change, the loop assigns
hold to price 100, then waits for saving from 1 ms to 31 ms. Price 101 arrives at 10 ms, but its condition check cannot start until 31 ms, producing enter at 32 ms. The time from input to condition-check completion is 22 ms.After the change, the input side hands the fixed price and decision result to the writer and proceeds to the next update. It checks the condition from 10 ms, when price 101 arrives, and produces
enter at 11 ms. The time from input to condition-check completion is 1 ms. Meanwhile, the writer is still saving the record for price 100.Both approaches evaluate the same two updates in order and save the same two records in order. All saves finish at 62 ms before the change and 61 ms after it; the work of performing two 30 ms saves remains. What improves is the time the next condition check spends waiting for the previous save.
This design can help when completion of the previous auxiliary save holds up the decision for a subsequent update that has already arrived. If the next decision does not depend on that save succeeding, the queue has space, and decision processing can run, the next decision can proceed during saving. Removing an unnecessary completion dependency is what can reduce latency. Handoff and scheduling also add costs, so verify the amount of improvement in your own implementation using the same inputs and work.
If input continues to exceed saving capacity, however, the finite queue fills and the input side also waits. Separating saving alone does not increase the destination's processing capacity. Different changes are needed when the next decision already progresses, or when CPU computation or locks are the main cause. Check both whether work was handed to separate processing and whether the dependency that held up decisions was reduced.[S04][S06][S07]
The writer receives the price and decision result fixed at that point in time. For the first update, that is a record such as
{ seq: 0, price: 100, decision: "hold" }. Even if the next update changes state.price to 101, the price in the record being saved remains 100. Passing the mutable state itself and reading the price again at save time can instead record the price from a different update.On normal completion, all records are saved. When the queue is full, the input side holds the current record and waits for space. If the writer closes or fails, reconcile what was saved with what remains unfinished. Sections 5 and 6 cover these boundaries.
3. Separate State Updates and Saving in TypeScript
Existing TypeScript code can also let state updates and auxiliary saving progress separately. Here we use six finite inputs: 100 → 101 → 102 → 100 → 101 → 99. The decisions are
hold, enter, hold, exit, enter, and exit, in that order. All inputs are ready at the start; there are no timers to simulate arrivals or artificial waits to slow saving. Each record is written to a real JSONL file, and saving waits through datasync().The purpose of this small runnable example is to trace decision order, the handoff for saving, full queues, failures, and shutdown. The speed of processing six inputs does not establish language rankings or production performance. The full version is the TypeScript implementation, with prices.json as its input.
First, combine the state update and record creation in one function. Both approaches use the same
decide, and only the input side updates previousPrice.typescript
export function decide(state: State, input: Input): Record {
let decision: Decision = "hold";
if (state.previousPrice !== undefined && state.previousPrice < 101 && input.price >= 101) decision = "enter";
else if (state.previousPrice !== undefined && state.previousPrice >= 101 && input.price < 101) decision = "exit";
state.previousPrice = input.price;
return Object.freeze({ seq: input.seq, price: input.price, decision });
}export function decide(state: State, input: Input): Record {
let decision: Decision = "hold";
if (state.previousPrice !== undefined && state.previousPrice < 101 && input.price >= 101) decision = "enter";
else if (state.previousPrice !== undefined && state.previousPrice >= 101 && input.price < 101) decision = "exit";
state.previousPrice = input.price;
return Object.freeze({ seq: input.seq, price: input.price, decision });
}The fields in this record are numbers and strings and are not modified after creation. In both approaches, JSON conversion also happens on the input side through the same
encode. The writer receives the finalized record and JSON string for that input. It does not read market state again after that state has changed.The flow before separation is shown below. Reporting lines are omitted to show only the dependency.
typescript
const record = decide(state, update);
const pending = encode(record);
await save(file, pending, options);
// この保存が終わってから、次のupdateへ進む。const record = decide(state, update);
const pending = encode(record);
await save(file, pending, options);
// この保存が終わってから、次のupdateへ進む。After separation, start one writer and a bounded queue. In Figure 2, input and decision processing are on the left, the queue is in the middle, and the writer is on the right. The input side still updates state; waiting for save completion moves to a separate role.
In the complete version, the following line starts the writer once before the input loop and retains the returned Promise.
queue exists in the separated version. At this point, the input loop proceeds without awaiting the writer's completion.typescript
const writerTask = queue === undefined ? undefined : writer(queue, file, options, emit);const writerTask = queue === undefined ? undefined : writer(queue, file, options, emit);Before proceeding to the next update, the input side checks the result of
queue.put. This put is a method in this runnable example, not a standard Node.js API. It accepts the record if there is space; if the queue is full, it retains the current record and waits. When the writer takes a record out, the input side can enqueue into the freed slot and proceed.This code has one input loop waiting for
put before proceeding to the next update. Simply placing it in an SDK callback invoked for each update without waiting for its Promise to complete also creates a new enqueue wait for each update. Section 7 examines the callers and upstream retention. From here onward, “accepted” means that the queue has taken ownership of the record, counted separately from save start and save completion.typescript
const wasAccepted = await queue.put(pending, () => emit("full_wait", record.seq));
if (!wasAccepted) {
unaccepted.push(record);
status = "closed";
break;
}
accepted.push(record.seq);const wasAccepted = await queue.put(pending, () => emit("full_wait", record.seq));
if (!wasAccepted) {
unaccepted.push(record);
status = "closed";
break;
}
accepted.push(record.seq);false means that the destination queue was closed and could not accept the record. Retain the record and stop processing subsequent inputs. This differs from waiting for space when the queue is full. emit and accepted record the execution order and accepted count for the finite inputs.Start only one writer and retain its Promise in
writerTask. Do not create a new save task for each input. Because the input side also awaits put one record at a time, at most one producer waits for space. This prevents unfinished saves from growing elsewhere after leaving the queue.For each record it takes, the writer calls the shared
save. The real I/O performed by this function is the same in both approaches.typescript
await file.writeFile(item.bytes);
await file.datasync();await file.writeFile(item.bytes);
await file.datasync();The writer takes the next record only after saving finishes, preserving write order for this file. There is no need to create a JavaScript worker for each record to separate asynchronous I/O. Consider worker threads when you want to move CPU-intensive JavaScript computation to another thread.[S12][S13]
When input ends, close the queue to further submissions and wait for the writer's result. The
close() used here does not discard the remaining records. The writer continues taking records until the queue is empty, then exits. Input exceptions and an early stop also enter this same shutdown path.typescript
queue?.close();
if (writerTask !== undefined) writes = await writerTask;
try { await file.close(); } catch (error) { fileCloseError = String(error); }queue?.close();
if (writerTask !== undefined) writes = await writerTask;
try { await file.close(); } catch (error) { fileCloseError = String(error); }This excerpt is inside
finally in the complete version. The file is closed after the writer's result is received. Section 6 covers recovery of records when saving fails.Simply replacing the call with
void save(record) does not control how many saves start concurrently, failures, order, or shutdown. The arrays holding input, decision history, and execution order in this example also exist to reconcile an educational example of at most six inputs. For a continuously running stream, replace them with a recording method that specifies count or retention limits.Mapping the Design to Existing Python Code
Python can establish the same boundary with
asyncio.Queue(maxsize=...) and a writer Task. Start one writer with asyncio.create_task(writer(...)) and retain the Task. Calling an async function alone does not start its execution in Python, so the startup method also needs to be mapped correctly.[S15][S16]Moving work to another Task can still occupy the same event loop if it directly performs synchronous I/O or long CPU work. Also check where the actual save API waits and executes.[S16]
| Design used here | Corresponding behavior to check in Python |
|---|---|
| Start one writer | Start it once with create_task, not once per update |
| Hand records over within capacity | One input producer uses await queue.put(record). If full, it retains the current record and waits |
| Recover records when closed | On Python 3.13 or later, handle QueueShutDown and retain the unaccepted record held by the producer |
| Process the remainder on normal shutdown | On Python 3.13 or later, after shutdown(immediate=False), continue consuming remaining records with get() and wait for the writer Task's result |
If saving fails, stop new submissions and recover the failed record and the remaining queue. A queue shutdown notification alone does not guarantee saving succeeded. This table is guidance for applying the design to Python, not a complete Python implementation or performance result. The runnable examples for an existing environment here are limited to Node.js.
4. Define Ownership and Execution Boundaries with Rust/Tokio
We continue with the same six prices as in Section 3. Input 100 → 101 → 102 → 100 → 101 → 99 and produce
hold → enter → hold → exit → enter → exit. Using the same prices and record IDs as Figures 2 and 3, we follow startup, handoff, and shutdown in Rust.[L06]The before/after versions of this Rust example call the same
decide, encode, and save. The sequential version finishes one save(...).await inside the input loop before proceeding. In the separated version, the input side makes the decision, encodes JSON, and hands the finalized record to one writer. The change separates where saving runs without changing the work performed.[L06]Hand Off from One Input Task to One Writer
First, map these four operations to the code. These roles are task responsibilities; they do not mean allocating a separate OS thread or CPU core to each.
| Operation | Where to trace it in the code |
|---|---|
| Start the writer once | Create the handoff with mpsc::channel, and pass the receiver and file to tokio::spawn |
| Decide in order and finalize the record for that point in time | decide and encode inside the input loop. Only this loop updates state |
| Hand over the current record | Proceed on success. On Full, retain the same record and wait for acceptance. On Closed, recover it and stop subsequent input |
| Check whether accepted saves have finished | End further submissions with drop(tx) and receive the writer's result with writer_task.await |
The following excerpt comes from
run_after in the complete runnable version. It omits input validation, file creation, initialization of state and reporting arrays, test stops and observations, and final Report construction. CAPACITY is 2. This setting lets us trace full-queue behavior with six inputs; it is not a recommended production capacity. options.failure and options.gate are injection settings for checking failures and full queues. Normal runs do not use them.rust
let (tx, mut rx) = mpsc::channel(CAPACITY);
let writer_task = tokio::spawn(writer(rx, file, options.failure, options.gate));
for &input in inputs {
let pending = encode(decide(&mut state, input));
decided.push(input.seq);
let sent = match tx.try_send(pending) {
Ok(()) => Ok(()),
Err(mpsc::error::TrySendError::Full(pending)) => {
tx.send(pending).await.map_err(|error| error.0)
}
Err(mpsc::error::TrySendError::Closed(pending)) => Err(pending),
};
match sent {
Ok(()) => accepted.push(input.seq),
Err(pending) => {
unaccepted.push(pending.record);
break;
}
}
}
drop(tx);
let writes = writer_task.await.map_err(|error| {
io::Error::other(format!(
"writer task failed; no complete report: {error}; accepted IDs: {accepted:?}"
))
})?;let (tx, mut rx) = mpsc::channel(CAPACITY);
let writer_task = tokio::spawn(writer(rx, file, options.failure, options.gate));
for &input in inputs {
let pending = encode(decide(&mut state, input));
decided.push(input.seq);
let sent = match tx.try_send(pending) {
Ok(()) => Ok(()),
Err(mpsc::error::TrySendError::Full(pending)) => {
tx.send(pending).await.map_err(|error| error.0)
}
Err(mpsc::error::TrySendError::Closed(pending)) => Err(pending),
};
match sent {
Ok(()) => accepted.push(input.seq),
Err(pending) => {
unaccepted.push(pending.record);
break;
}
}
}
drop(tx);
let writes = writer_task.await.map_err(|error| {
io::Error::other(format!(
"writer task failed; no complete report: {error}; accepted IDs: {accepted:?}"
))
})?;mpsc::channel creates the sender tx and receiver rx, and tokio::spawn starts one writer. Ownership of the receiver and file is transferred to the writer. Only the input loop updates the price state; it is not shared with the writer.[S03][S04][L06]decide applies the current price and finalizes the decision, while encode packages that record and the JSON bytes into Pending. The writer passes each item received through recv().await to the shared save and takes the next item only after write_all → flush → sync_data finishes. Saving does not read the price state again after it has changed.[S09][S10][L06]If
try_send succeeds, the input side can move to the next price. When full, Full(pending) returns the same unaccepted value. Pass that value to send(pending).await and wait for capacity, without repeating the decision or creating another waiting task for each update. The send Future owns that record while waiting. Tokio can progress the writer while the input side waits, but if saving remains stalled, the input side keeps waiting too.[S04][S05][L06]If the channel closes, recover the value from
Closed(pending) or the error from the pending send. map_err(|error| error.0) extracts the unaccepted Pending held by the send error so both closure paths reach the same recovery handling. Retain the already-decided record in unaccepted and do not proceed to subsequent input. After break exits the input loop, execution still continues to drop(tx) and writer_task.await. The former ends further submissions; the latter checks the writer's shutdown result. Check successful submission, save completion, and task completion separately.[S04][S06][S34][L06]This example does not cancel a pending send. If another branch of
select! or a task abort drops the send Future, the record it owns may also be lost. On a save error, the writer recovers the failed record and returns; inspect the result through writes.error and each category in the Report. If the task itself panics, for example, and writer_task.await yields JoinError, the example returns an error rather than a complete Report. Do not treat this example as guaranteeing recovery from panics, forced termination, or crashes.[S04][S34][L06]Transferring Ownership Does Not Require a Deep Copy
Pending contains the finalized record and a Vec<u8> and is a non-Copy type. Once the channel accepts it, the input side cannot continue using that same value as its owner. If the channel is full or closed, the input side receives the returned value and can handle its ownership again. This connects “the record still held by the input side” and “the record handed to the writer” to types and code.[S05][S22][L06]This handoff does not require a deep copy of the entire record. However,
encode allocates the JSON bytes. Using ownership transfer alone does not make the whole system zero-copy or allocation-free.The price example handles at most six small records with fixed fields. Because only the input side holds mutable state, there is no need to share market state with the writer through Arc or Mutex. Section 7 separately discusses the byte limit added when adapting the design to variable-length Geyser updates.
Arc, Send/Sync, and Tokio Have Different Roles
You can use
Arc<Config> to share data such as a large immutable configuration across multiple roles. Arc::clone adds a shared owner of the same allocation; it does not deeply copy the contents. A separate mechanism is required for safe concurrent mutation of the inner value, and atomic reference-count operations also have a cost. In the accompanying Geyser replay example, Arc shares the Semaphore for the byte budget, while Semaphore itself provides safe acquisition, release, and closure of that budget.[S01][S11][S30][L04]| Mechanism | What it controls | What it does not automatically guarantee |
|---|---|---|
| Ownership transfer | Which role holds the record and bytes | Zero-copy, zero allocations, or successful saving |
Arc | Shared ownership of the same data | Safe concurrent mutation of the inner value |
Send | Whether a type permits an owned value to move between threads | Execution on another thread |
Sync | Whether a type permits shared references to be used across threads | Update order or freedom from deadlock |
| Tokio | Progress of async tasks, I/O waits, and channels | A dedicated CPU, priority, or a decision deadline |
Send and Sync are properties of types, Arc is a shared-ownership tool, and Tokio is the execution runtime. Ordinary tokio::spawn requires Send + 'static for the Future and its output. Here, 'static is a type bound that prevents the task from depending on short-lived borrows. It does not mean the value lives forever; values transferred into the task by ownership can be released when no longer needed.[S02][S03]Both the before and after versions of this Rust price example run on
current_thread. Even with one async execution thread, another task can progress while I/O is pending. File I/O also involves Tokio's internal blocking execution resources, so this does not mean the entire process uses one OS thread. The accompanying Geyser replay example uses multi_thread with two workers; record these execution settings separately.[S08][S09][L04][L06]TypeScript Can Also Separate the Work. Why Recommend Rust First?
The design that separates saving can also be implemented in TypeScript. Changing only the language while preserving the same save dependency leaves the requirement to wait for the previous save in place.
When building a new low-latency reception and decision engine in depth, we recommend Rust first. It lets you connect which values are owned, copied, or shared to types and handoffs: extract only the fields needed for decisions, transfer ownership of bytes to saving, fix who updates state, and constrain the execution placement and concurrency of CPU work. You can examine these choices individually and focus improvements where they are needed.[S01][S02][S07][S11][S22]
For example, if the input side tries to modify the same
pending after successfully sending it, Rust rejects the ownership error at compile time. Connecting a design with one decision task and a bounded queue to type checking of value handoffs is an advantage when refining an implementation.[S22]For existing TypeScript or Python code, first fix the dependencies in the current language and check whether the required input conditions meet the decision deadline, ordering, and retention requirements. If separating auxiliary saving meets those requirements, you can continue with that implementation. If it does not, and costs remain in a specific stage such as decoding or copying, consider extracting that stage into Rust. Include handoff and operating costs in the decision; there is no assumption that the UI, configuration, and monitoring must all be rewritten at once.
Do not reinterpret the reasons for recommending Rust first as proof of a speed advantage on a particular input. Show the ability to control copying, allocation, sharing, synchronization, and execution placement separately from what was actually reduced and by how much, tying each to the implementation and verification results.
5. Hold One Record When Full and Resume When Space Opens
A bounded queue can absorb a temporary increase in input. Once its capacity is exhausted, however, the input side must also wait for space. Both Tokio's
send().await and the TypeScript put in this example introduce that wait. Separating saving does not make the design unconditionally free of waits.[S04]Follow the six inputs as they are handed to a queue with capacity 2. Record ID 0 is
hold for price 100, ID 1 is enter for price 101, ID 2 is hold for price 102, and ID 3 is exit for price 100. They are followed by ID 4, enter for price 101, and ID 5, exit for price 99. The ID is a sequence number in input order, not the price.While the writer is writing ID 0, IDs 1 and 2 fill the two slots in the queue. The input side has finished the decision for ID 3 but cannot yet hand it to the writer. It therefore holds ID 3 and waits without proceeding to ID 4 or later.
When saving ID 0 finishes and the writer takes ID 1, one slot opens in the queue. The input side hands over the ID 3 it has retained and proceeds to ID 4. It does not repeat the decision for ID 3. It retains the same record and continues the handoff.
Only one item of work is waiting on the input side at this point. Continuing to create a task that waits for
send for every update merely moves an unbounded wait outside the queue. The input side here does not handle the next input until the current submission finishes.| Writer state | Input-side behavior |
|---|---|
| The queue has space | Hand over the finalized record and proceed to the next input |
| The queue is full and the writer is running | Retain the current record, wait for space, and resume |
| The writer has closed | Retain the unaccepted record, or its recovery source and ID, and stop subsequent input |
Waiting when full is called backpressure. If input continues to exceed saving capacity, waiting time grows too. To retain all required records with finite memory, you must decide where to control the load: make upstream wait, stop accepting input, or provide stored input from which recovery is possible.
Queue capacity bounds the records inside the queue. The record being saved, the one held by the input side, variable-length payloads, receive buffers, and aggregated results consume additional memory. Implementations handling real data need byte limits as well as count limits.[S04][S06]
In this small example, all input remains in a file. With live gRPC or WebSocket input, check who retains updates while the application waits and how far upstream that wait can propagate. If the SDK has already discarded updates, bounding the save queue alone does not retain every update.
Fetching the latest price after a gap also differs from reconstructing the decisions made during that gap. If the price moves 100 → 101 → 100 while processing is stopped, the latest price of 100 alone cannot reconstruct the intervening
enter and exit. If the requirement is to preserve decisions for every update, processing cannot resume until the necessary history has been recovered.Recovering History Does Not Establish That It Is Valid for Current Decisions
In Figure 3, what resumes when space opens is the input processing that had been stopped. In a live trading application, you also need to check whether updates remain fresh enough to use for decisions, in addition to processing them without losing records. Even if replaying old inputs in order can recover state, the
enter or exit conditions reached during that replay may not be usable directly for current orders.| Information the application needs | What to define when returning from a full queue or a gap |
|---|---|
| Every intermediate transition is needed for decisions | Recover the required history and preceding state, then process them in order. Define whether results produced during historical replay may be used for orders separately from current decisions |
| Decisions can start from the latest state | Verify that specification, resynchronize to a consistent latest state, and then make decisions. Do not treat this as having reconstructed intermediate condition triggers |
| Current decisions have a freshness deadline | Define the maximum acceptable update age and the decision deadline, along with conditions for stopping decisions and resuming after those limits are exceeded |
Increasing capacity lets you retain more records, but it also allows old updates to wait longer. Alongside record counts and bytes, inspect how long the oldest update has been waiting. Do not silently discard required records after a deadline; separate record retention from the conditions under which current decision processing may run. This educational example processes all six inputs in order. It does not implement refetching live input or automatically resuming orders.
6. Distinguish Successful Submission, Save Completion, and Shutdown
When submission succeeds, the record has only been handed to the writer. Count a save as successful only after the specified write and synchronization operations finish. In this TypeScript example, each record's completion condition is
writeFile → datasync; in the Rust verification, it is write_all → flush → sync_data.[S09][S10][S12]Tokio's
flush completes in-progress writes and is distinct from sync_data, which requests synchronization from OS buffers to the device. We can verify that these APIs succeeded, but that does not amount to testing power loss, directory synchronization for a newly created file, or recovery from a failed device.Normal shutdown ends new input processing, closes further submissions, and waits for the writer to drain accepted records. With Tokio, release every send handle and await the writer's
JoinHandle. In the TypeScript example, call queue.close() and then await writerTask. Input processing must also enter this shutdown path if it ends with an exception or an early stop.[S03][S06]On Save Failure, Separate Unwritten Records from Unknown Outcomes
If saving fails, the writer closes the queue. The input side waiting for space also learns that the queue has closed and stops subsequent processing. The TypeScript and Rust price examples retain the complete records for unwritten, unknown-outcome, and unaccepted saves in the Report. For unprocessed inputs, Rust retains the entire Input in the Report, while TypeScript uses the Report's IDs and the original input file to trace them. After closure, the Rust writer also takes the remaining queue entries and recovers them as unwritten records before exiting.[S06][L03][L06]
The accompanying Rust Geyser replay example retains unfinished IDs and states in a ledger and preserves the original inputs in immutable protobuf files. Because the retention methods differ, check whether each reported ID leads back to its original input or record. Dropping a receiver handle alone does not save unread payloads. For live input, separately design refetching or retention of unsaved payloads.[S06][L04]
If a record fails before writing starts, it is known to be unwritten. An error after writing starts, however, may leave a partial write. If synchronization cannot be confirmed after the write, the specified save-completion condition has not been established either. These examples retain such records as unknown save outcomes and do not count them as successes.
At shutdown, classify input IDs into the following five states. Verify that the five sets are disjoint and cover all original inputs.
| State at shutdown | Meaning |
|---|---|
| Save complete | The decision and the defined write and synchronization operations have completed |
| Accepted, not written | Handed to the writer but still unwritten because of a pre-write failure or recovery from the remaining queue |
| Accepted, save outcome unknown | The specified save completion cannot be confirmed, for example after a failure following the start of writing |
| Decided, not accepted for saving | The decision is complete, but closure prevented handoff to the writer |
| Unprocessed | The input remains, but state application and decision processing have not occurred |
The decided count is not a separate set to add to these five. It counts inputs in the first four categories whose decisions have finished. Check it separately from the number handed to the queue and the number successfully saved.
Blindly retrying an append with an unknown outcome can create duplicates or incomplete lines. Recovery uses record IDs, destination transactions, and the deduplication contract. These examples cover identifying and reporting unfinished items after stopping; they do not implement automatic retries or recovery after a crash.
If the storage destination does not return, you also need a separate decision about how long shutdown should wait. Writing
await writerTask or task.await alone does not solve shutdown deadlines or safe cancellation of I/O that has already started. If needed, verify what can be retained and reported at the deadline, together with the storage destination's contract.7. Find the Place to Improve in Real Receive Code
When introducing this separation into your own trading application, trace from the function that receives an update back to the code that calls it. Even if the save function contains
await, whether its caller waits for completion changes both the problem and where to fix it. Start with these three checks.| What to check in your code | Change to consider if confirmed |
|---|---|
| Does an already-arrived next update have to wait for the previous auxiliary save before its decision can be made? | Remove the save wait that the decision does not require and hand a finalized record to a separate writer |
| Does the next decision progress while unfinished saves keep accumulating? | Bound concurrent saves and waiting work, and decide where input is retained when full |
| Does the receive side discard necessary updates before they reach the save queue? | Trace back to the discard branch and revisit input retention, refetching, and the conditions for resuming decisions after a gap |
The same symptom of “not keeping up with updates” can require these different fixes. Correlating the next update's processing start, save start and completion, queued work, and discarded updates narrows down where to improve.
Adding Saving to the TypeScript Receive Sample
The official Solana Stream SDK's Geyser receive samples also use a queue to hand received updates to processing. In the inspected version of the TypeScript sample,
runHandler calls onUpdate for each update and attaches error handling to the returned Promise, but does not wait for it to finish. Consequently, even with saving implemented as below, subsequent update processing may begin before the previous save finishes.[S24][S25]The following insertion illustrates the problem.
decideAndSnapshot is an explanatory function name representing the existing application's state update, decision, and creation of a finalized record.typescript
// この形を登録しただけでは、保存の並行数と順序は決まらない。
onUpdate: async (update) => {
const record = decideAndSnapshot(update);
await saveAuxiliary(record);
}// この形を登録しただけでは、保存の並行数と順序は決まらない。
onUpdate: async (update) => {
const record = decideAndSnapshot(update);
await saveAuxiliary(record);
}If unfinished saves accumulate here, this is the second case in the table above. A finite receive queue does not bound the Promises or saving operations after entries are taken from it. This sample's
processedUpdates also cannot be used as the number of completed saves.[S24]In this case, consider a design where one decision task creates finalized records in order and hands them to a bounded save path. Simply putting the
await queue.put(...) from Section 3 in each callback also creates more waiting callbacks for each update when the queue is full. At the point responsible for handing off input, prevent progress to the next input until the current record is accepted, and check where on the receive side input can be retained in the meantime.In the inspected TypeScript sample, within
processEvents, eventQueue.shift() takes an update and passes it through processEvent, runHandler, and onUpdate. Find the corresponding point in your own implementation that hands the next update to processing. Also check whether the Promise waiting for acceptance into the save path is returned to the caller, allowing the wait to propagate back to the component taking updates. If that component is changed to wait for save acceptance, updates accumulate in the SDK queue in front of it. Address retention upstream of the stopped dequeue point as well as the save function itself.[S24]For example, if you confirm that upstream can retain updates not yet taken and that one processing task can wait before fetching the next update, proceed in the following order. This is a procedure for locating the changes, not complete code that replaces an SDK-specific API.
- The input task takes the next update.
- Update state, check the conditions, and finalize the record for that point in time.
- Retain the current record until the save path accepts it. Do not create more waiting tasks for each update.
- Once accepted, proceed to the next fetch. On closure, recover the unaccepted record, stop subsequent input, and check the writer's shutdown result.
Use the SDK's and provider's contracts to determine what happens to updates while this task waits.
| Confirmed receive-side condition | What must be established before connecting |
|---|---|
| Taking the next update can wait, and the necessary updates can also be retained upstream | Concentrate the wait in one dequeue task. Also check upstream buffers' count and byte limits and their behavior when full |
| Callbacks cannot be stopped, but the necessary history can be fetched again | Retain the capture position, missing range, and preceding state, and create a path from stopping decisions through history recovery to resumption |
| Callbacks cannot be stopped and the necessary history cannot be recovered | The current connection does not meet the conditions for retaining every update. Revisit the subscription scope, input-retention method, and receive-side capacity |
Do not assume that the SDK supports pausing or refetching history. Check not only whether an API exists, but also where updates remain while stopped and whether the required range can be recovered. If the specification permits resynchronizing to the latest state, treat that as the separate condition in Section 5; do not equate it with retaining every update.
The purpose of this change is to control unfinished work and save order. Changing saves to run one at a time changes the performance of I/O that was already concurrent, so measure decision latency and save throughput again.
Furthermore, both the Rust and TypeScript samples in the inspected version contain a path that discards ordinary updates when the internal queue is full. Adding a save queue downstream does not recover updates already lost upstream. If intermediate updates are also required for decisions, include full-queue retention and refetching in the design. This is the behavior of the referenced samples, not a restriction shared by every Geyser client.[S24][S25]
For live input, check who retains updates while stopped and where processing can resume. Unlike an educational example whose input file remains available, simply stopping the loop does not necessarily preserve unprocessed updates. If the required history cannot be recovered, distinguish returning to the latest state from reconstructing decisions during the missing interval.
The referenced sample version, function mapping, and full-queue branches are documented in the source inspection notes and sources [S24][S25]. Check the invocation pattern in your own version and determine whether the same pattern applies.
Adapting the Price Example to Geyser-Format Updates
The separation so far is between ordered input processing and saving its fixed results. The accompanying Rust replay example decodes Geyser-format transaction updates retained in files and extracts calls to a specified program. Its computation differs from checking price conditions, but the relationship is the same: one input task fixes the result and hands it to one writer.[L04]
| Role | Six-price example | Geyser-format replay example |
|---|---|---|
| Input | Price updates with IDs | Protobuf updates saved in files |
| Input-side work | Apply the price and finalize the decision | Decode the update and extract program calls |
| What is handed to saving | The price and decision result for that update | The result extracted from that update |
| Save order | Save one record at a time in input order | Save one record at a time in input order |
| What is bounded | At most six inputs and a capacity-2 queue of small records | The total variable-length bytes handed over, in addition to the queue's record count |
The before/after versions of the Geyser replay example also use the same
process_update, encode_result, and save. They first reserve one queue slot with try_reserve; if full, they call reserve().await while the input side continues to hold the current bytes. Once a slot is obtained, slot.send(Pending { ... }) transfers ownership. The timing of the value handoff differs from the price example's try_send, but both retain track of the current item before acceptance and do not proceed to subsequent input early.[S04][S05][L04]Variable-length records need a byte limit separate from the record count. The verification settings for this replay example are a queue capacity of 64 records and a 1 MiB byte budget enforced by Semaphore. The budget covers the current input-side record after acquiring a permit, records in the queue, and the record being saved.
Pending holds the permit, and releasing it after processing returns the capacity. If a single record exceeds the limit, the example returns an error instead of waiting forever for space.[S30][L04]This 1 MiB is not a memory limit for the entire process. The current record before acquiring byte capacity, decoded input, the original fixture, and the ledger consume memory separately. Neither 64 records nor 1 MiB is a value to adopt directly in production. Choose them based on actual input sizes, acceptable backlog, and saving capacity.[L04]
This replay example is applied educational material for checking how the boundaries work with local input. It is not a complete adapter that can be connected directly to a live SDK callback. Implement the invocation pattern, upstream retention, and conditions for resuming after a gap examined earlier to fit your own receive path.
8. Check Processing Order and Retention with Small Inputs
After restructuring the design, first verify that the same input still produces the same decisions and saved records. Even if separating saving allows the next decision to progress sooner, a change in decision order or saved contents would defeat the intended change. A small input lets you follow every record through to the end.
Give Both the Sequential and Separated Versions the Same Six Inputs
Give the TypeScript and Rust price examples the same six inputs: 100 → 101 → 102 → 100 → 101 → 99. Within each language, the sequential and separated versions use the same decision function, JSON encoding, and save function. The expected decisions are
hold → enter → hold → exit → enter → exit.[L03][L06]Extract the ZIP of all implementation examples and run the following commands inside
typescript. The execution instructions use Node.js's TypeScript execution feature. The distributed example has been verified with Node.js v24.22.3.bash
node example.ts --mode before --out run-before
node example.ts --mode after --capacity 2 --out run-after
node --test checks/example.test.mjsnode example.ts --mode before --out run-before
node example.ts --mode after --capacity 2 --out run-after
node --test checks/example.test.mjsInspect saved contents and order in
records.jsonl, and decisions, saves, unfinished IDs, and execution order in report.json. On normal completion, both approaches have been verified to decide and save all six inputs in the same order, with every byte of the JSONL matching. The example makes no external connections and uses real file writes and datasync().[L03]Run the Rust version inside
price-rust in the same ZIP. Also see the execution instructions for the same six prices. It has been verified in a release build with Rust 1.100.0, Tokio 1.54.1, and dependencies pinned by Cargo.lock.[L06]bash
cargo build --release --locked
cargo run --release --locked -- before out/before
cargo run --release --locked -- after out/after
cargo test --release --lockedcargo build --release --locked
cargo run --release --locked -- before out/before
cargo run --release --locked -- after out/after
cargo test --release --lockedFor Rust as well, inspect
records.jsonl and report.json in each output directory. The decisions for all six inputs, save order, and every JSONL byte match between the sequential and separated versions. Matching the same expected values in both languages verifies that the educational examples perform the same work. Processing times and language speed rankings are not compared. Use a new output directory when running again.[L06]Fill the Queue and See Where the Current Record Remains
The full-queue test uses a gate that releases the writer manually. As in Figure 3 in Section 5, it stops the writer before ID 0 begins writing, puts IDs 1 and 2 into the queue, and leaves ID 3 on the input side. It verifies that processing does not proceed to ID 4 and that, after the writer resumes, the input side can hand over the retained ID 3 and continue.
This verifies that decisions progress while the writer is held as long as capacity remains, and that the input side retains the current record and waits once capacity is exhausted. Separation and Full handling can be checked without comparing elapsed times.
The Rust Full test records the following observation in
report.json. It is one entry extracted from the full array.[L06]json
{"current_seq":3,"decided_count":4,"accepted_count":3,"queue_depth":2}{"current_seq":3,"decided_count":4,"accepted_count":3,"queue_depth":2}Four inputs, through ID 3, have been decided; three, IDs 0–2, have been accepted; and two, IDs 1 and 2, are in the queue. The pending send holds the current ID 3. Save completion is checked separately in
writes.saved. In the report after the gate is released and processing ends normally, IDs 0–5 appear there in order. This run also has an observation for ID 2 at the beginning of the full array. Because the test waits for an observation with current_seq equal to 3 before resuming saving, do not read the first entry as the state for ID 3.[L06]| Scenario to test | Behavior to verify |
|---|---|
| Normal completion | Decide all original inputs in the same order and save the same records |
| Full queue | Retain the current record, do not proceed to the next input, and hand over the same record when space opens |
| Writer closure | Retain the unaccepted record or its recovery source and ID, and stop subsequent input |
| Failure before saving | Distinguish records not yet written from inputs not yet decided |
| Failure after writing but before synchronization is confirmed | Retain an unknown outcome and do not count it as save completion |
| Early stop or input-processing exception | Enter shutdown, drain accepted records, and check the writer's result |
In every case, check whether the five states from Section 6 cover all original inputs without overlap. This avoids changes that appear faster because they lose required work. The TypeScript price example checks every scenario in the table. The Rust price example uses six functional checks to verify normal completion, resumption from Full, Closed, failures before saving and after writing, and input stopping after three records. Recovery from input-processing exceptions or panics is outside this Rust price example's verification scope.[L03][L06]
The accompanying Geyser replay example uses explicitly identified synthetic protobuf input to check extracted results, saved contents, order, count and byte limits, failures, and stopping. Its inputs and work are distinguished from the new example that verifies price decisions.[L04]
Verify Whether Waits Decreased in Your Own Implementation
When applying the design, use the measurement points in Section 1 to see whether the next decision begins without waiting for the previous save to finish. Use the same input, decisions, and save conditions before and after, and check decision completion separately from completion of all saves. Including handoff costs and waits for full queues lets you determine which waits decreased and which remain in your implementation.
Original run records, counts under failure, build conditions, and additional measurement-method notes are collected in the validation notes. The diagrams in the main article are explanatory models for tracing dependencies; their assumed times are not improvement measurements for a live environment.
9. Find the Next Wait and Choose Between Concurrency and Parallelism
Separating waits for saving does not eliminate every delay after reception. Measure decoding, state updates, condition checking, preparation of data for saving, queues, and locks again to find the next place consuming time. Also check whether moving an operation into another task has increased handoff or synchronization waits.
Concurrency can progress other work during an I/O wait; the writer in this article is an example. For work that occupies the CPU for a long time, consider reducing the computation or running it on separate execution resources. Tokio's
spawn does not create a dedicated thread for each task, and adding async alone does not move heavy computation to another CPU.[S03][S07][S08]For example, when preparing or compressing a large amount of data on another CPU, define how much data can be handed over while retaining the input, the number of workers, and the queue limit. When choosing Tokio's
spawn_blocking or execution resources for CPU work, bound not only the number of running operations but also the work waiting to start. Do not assume a blocking operation that has already started can be easily cancelled.[S07]State updates and condition checks that depend on the previous update's result must still preserve order. Even when independent computations run in parallel, define the order in which results are applied, the treatment of stale results, and resynchronization after missing input. A required save before a decision cannot have its dependency removed. Check whether waits decreased while the necessary dependencies were preserved, not simply whether more operations were started.
Node.js worker threads and separate Python processes can also separate CPU work. Include conversion and copying of transferred data, queue waits, and the time to return results in the comparison. Separately check the conditions imposed by the Python build, GIL, and extension modules in use.[S13][S16][S17]
For a new low-latency reception and decision engine, Rust is the first choice. In an existing TypeScript or Python application, one approach is to retain the UI, configuration, monitoring, and research work while extracting into Rust the parts that measurements show need it. Separate the improvement from the design change from the difference in the implementation after migration, and compare using the same inputs, work, and correctness requirements. Verification of separated I/O saving does not establish the benefit of CPU parallelization. Check with the actual payloads and processing you will use.
10. Appendix: Diagnose and Improve Your Code with an AI Agent
Each of the two prompts can be given independently to an AI that can read your repository. The first covers diagnosing waits, making minimal changes, and comparing under the same conditions; the second covers full queues, failures, and shutdown. Carry forward existing permissions and working rules, and judge proposed changes by which waits decreased and whether order and records were preserved.
1. Diagnose Waits After Reception and Implement the Required Separation
text
Investigate the path in this repository from receiving an update through state updates and decision processing. Identify where waiting for saving or data preparation to finish delays the next update, or where unfinished auxiliary work keeps accumulating. Carry the work through to an evidence-based minimal fix and a before/after comparison under the same conditions.
First check the existing working rules, permissions, uncommitted changes, and versions of the language, runtime, SDK, and dependencies. Do not overwrite other changes. Production changes, load tests against external services, transaction submission, and paid contracts are outside scope. Proceed with the necessary local investigation, modifications, and small replay checks. Do not output private keys, credentials, or customer data.
1. Trace the actual files and functions for reception, decoding, state updates, decisions, and saving, including their callers. Check whether callers wait for the Promise/Future returned by an async function, invoke it independently for each event, and when they take items from intervening queues. Do not infer from the name async alone that the next reception is blocked or that the work runs on another thread. Also check whether the SDK's processed count includes save completion and whether its default full-queue handling discards updates.
2. Distinguish I/O waits, CPU occupancy, queue waits, and lock waits, and separate confirmed facts, hypotheses about causes, and unmeasured areas. Use consumers, recovery processing, README files, specifications, and existing tests to classify records that must be durable before a decision versus auxiliary records that may be saved later. If the required update order, stopping decisions and resynchronizing after gaps, or the save-failure contract is unclear, investigate the evidence without removing the dependency. Also investigate the maximum acceptable update age, decision deadlines, and the conditions for resuming current decisions after history recovery. If these are undefined, report them as undefined rather than inventing values.
3. Before making changes, fix the finite input and expected correctness results. Distinguish input captured from a real stream from input created for illustration, and record the input hash, count, order, and capture range. Do not call the entry point where an SDK delivers decoded values a wire-reception timestamp, or call re-encoded values the original wire bytes. Where usable input or an execution environment is unavailable, do not label an unexecuted check as a completed measurement.
4. Define measurement start and end points. Using the monotonic clock of the same process, distinguish the handoff/replay schedule, decision start and completion, save acceptance, and save start and completion. If reproducing arrival intervals, do not delay the schedule to match completion of the previous save. If measuring a finite sequence with all inputs ready at the start, state that condition and do not call it latency from actual reception. Do not draw conclusions about a language's computation speed from numbers that mix timer-resumption time, actual processing, and real I/O. Accompany p50/p95/p99 with sample counts and calculation methods, and reconcile processed, unprocessed, discarded, duplicate, and save-unconfirmed IDs, decision results, order, and saved contents. The denominator for the fraction completed within the deadline is all target inputs. For queue counts, bytes, the oldest wait, CPU, and memory, distinguish what was verified from what was not measured.
5. First make the minimal fix in the existing environment for the confirmed cause. If separating auxiliary work, define ownership of immutable records, a single updater of mutable state, a bounded queue, and the number of writers. send().await waits when full. For Full from a nonblocking submission, use the contract to decide whether to retain the returned record and wait or stop, and report either the waiting time or the unprocessed range. For Closed, retain the unaccepted record and handle stopping and recovery. Also check upstream retention. Distinguish successful submission from save completion, and write completion from sync/commit. Submission failure after a decision is “decided, not accepted for saving”; do not count it as unprocessed input. Do not make a change appear faster by using an unbounded queue, a waiting task per update, or discarding required updates.
6. Compare before and after using the same input, arrival conditions, work, correctness requirements, and save-completion conditions. Test normal operation, a short burst, a full queue, save failure, writer closure, and draining on normal shutdown; reconcile the location and order of every input. Check whether shutdown handling is reached even on an input exception or early return, and retain unknown save outcomes as unknown. Also report conditions under which there is no improvement.
7. If costs remain after improving the existing environment and the requirements justify it, evaluate extracting the low-latency reception and decision processing into Rust. Specify the target processing and costs of copying, allocation, sharing, synchronization, and boundary crossings. Record the release build and dependency lock, runtime, and SDK/native layers, and compare under the same conditions. Arc provides shared ownership, Send/Sync are type properties, and Tokio is the execution runtime. Arc alone does not guarantee safe concurrent mutation of inner values or zero-copy. Do not conclude that a complete migration is needed or rank languages by speed without measurement evidence.
Finally, report the diagnostic evidence, modified files and functions, reproduction commands, before/after results, correctness and retention checks, unmeasured scope, and the specific problems that remain. Do not unnecessarily change areas that have no problem or are already separated. If the evidence does not support an article's or proposal's central claim, do not treat it as complete merely by adding limitations; explicitly state whether that claim is retained or rejected and which work remains unfinished.Investigate the path in this repository from receiving an update through state updates and decision processing. Identify where waiting for saving or data preparation to finish delays the next update, or where unfinished auxiliary work keeps accumulating. Carry the work through to an evidence-based minimal fix and a before/after comparison under the same conditions.
First check the existing working rules, permissions, uncommitted changes, and versions of the language, runtime, SDK, and dependencies. Do not overwrite other changes. Production changes, load tests against external services, transaction submission, and paid contracts are outside scope. Proceed with the necessary local investigation, modifications, and small replay checks. Do not output private keys, credentials, or customer data.
1. Trace the actual files and functions for reception, decoding, state updates, decisions, and saving, including their callers. Check whether callers wait for the Promise/Future returned by an async function, invoke it independently for each event, and when they take items from intervening queues. Do not infer from the name async alone that the next reception is blocked or that the work runs on another thread. Also check whether the SDK's processed count includes save completion and whether its default full-queue handling discards updates.
2. Distinguish I/O waits, CPU occupancy, queue waits, and lock waits, and separate confirmed facts, hypotheses about causes, and unmeasured areas. Use consumers, recovery processing, README files, specifications, and existing tests to classify records that must be durable before a decision versus auxiliary records that may be saved later. If the required update order, stopping decisions and resynchronizing after gaps, or the save-failure contract is unclear, investigate the evidence without removing the dependency. Also investigate the maximum acceptable update age, decision deadlines, and the conditions for resuming current decisions after history recovery. If these are undefined, report them as undefined rather than inventing values.
3. Before making changes, fix the finite input and expected correctness results. Distinguish input captured from a real stream from input created for illustration, and record the input hash, count, order, and capture range. Do not call the entry point where an SDK delivers decoded values a wire-reception timestamp, or call re-encoded values the original wire bytes. Where usable input or an execution environment is unavailable, do not label an unexecuted check as a completed measurement.
4. Define measurement start and end points. Using the monotonic clock of the same process, distinguish the handoff/replay schedule, decision start and completion, save acceptance, and save start and completion. If reproducing arrival intervals, do not delay the schedule to match completion of the previous save. If measuring a finite sequence with all inputs ready at the start, state that condition and do not call it latency from actual reception. Do not draw conclusions about a language's computation speed from numbers that mix timer-resumption time, actual processing, and real I/O. Accompany p50/p95/p99 with sample counts and calculation methods, and reconcile processed, unprocessed, discarded, duplicate, and save-unconfirmed IDs, decision results, order, and saved contents. The denominator for the fraction completed within the deadline is all target inputs. For queue counts, bytes, the oldest wait, CPU, and memory, distinguish what was verified from what was not measured.
5. First make the minimal fix in the existing environment for the confirmed cause. If separating auxiliary work, define ownership of immutable records, a single updater of mutable state, a bounded queue, and the number of writers. send().await waits when full. For Full from a nonblocking submission, use the contract to decide whether to retain the returned record and wait or stop, and report either the waiting time or the unprocessed range. For Closed, retain the unaccepted record and handle stopping and recovery. Also check upstream retention. Distinguish successful submission from save completion, and write completion from sync/commit. Submission failure after a decision is “decided, not accepted for saving”; do not count it as unprocessed input. Do not make a change appear faster by using an unbounded queue, a waiting task per update, or discarding required updates.
6. Compare before and after using the same input, arrival conditions, work, correctness requirements, and save-completion conditions. Test normal operation, a short burst, a full queue, save failure, writer closure, and draining on normal shutdown; reconcile the location and order of every input. Check whether shutdown handling is reached even on an input exception or early return, and retain unknown save outcomes as unknown. Also report conditions under which there is no improvement.
7. If costs remain after improving the existing environment and the requirements justify it, evaluate extracting the low-latency reception and decision processing into Rust. Specify the target processing and costs of copying, allocation, sharing, synchronization, and boundary crossings. Record the release build and dependency lock, runtime, and SDK/native layers, and compare under the same conditions. Arc provides shared ownership, Send/Sync are type properties, and Tokio is the execution runtime. Arc alone does not guarantee safe concurrent mutation of inner values or zero-copy. Do not conclude that a complete migration is needed or rank languages by speed without measurement evidence.
Finally, report the diagnostic evidence, modified files and functions, reproduction commands, before/after results, correctness and retention checks, unmeasured scope, and the specific problems that remain. Do not unnecessarily change areas that have no problem or are already separated. If the evidence does not support an article's or proposal's central claim, do not treat it as complete merely by adding limitations; explicitly state whether that claim is retained or rejected and which work remains unfinished.2. Check That Updates and Records Remain Accounted for Through Full Queues, Failures, and Shutdown
text
Examine the separation of reception and decision processing from auxiliary saving in this repository, and verify that updates and records remain accounted for when the queue is full, saving fails, the writer closes, or processing ends normally. Make minimal fixes only for defects supported by evidence, and verify before and after using the same small local input.
Check the existing working rules, permissions, uncommitted changes, and versions of the language, runtime, SDK, and dependencies. Do not overwrite other changes, and limit modifications to the retention and shutdown conditions in this task. Production changes, load tests against external services, transaction submission, and paid contracts are outside scope. Proceed with the necessary local investigation, modifications, and replay checks. Do not output private keys, credentials, or customer data.
1. Identify the actual files and functions, the owner of received input, the updater of mutable state, queue capacity and the per-record byte limit, the number of writers, retries, and shutdown paths. Also investigate whether SDK callbacks wait for async processing to finish, whether processed counts mean save completion, and whether an upstream queue discards items when full. Separate confirmed facts, hypotheses, and unmeasured areas. If saving before a decision is required, preserve that dependency and do not treat the record as auxiliary.
2. Classify the same input IDs as unprocessed; decided, not accepted for saving; accepted, not written; accepted, save outcome unknown; or save complete. Verify that these five sets are disjoint and cover all input, and detect discards, duplicates, order violations, and double-counting. Do not arbitrarily classify records with unknown outcomes, such as partial writes, as successful or unwritten. Do not add the decided count on top of the five sets. Local sequence numbers assigned to a real stream identify the captured sequence; they are not proof that every server update was captured. Record disconnected, retransmitted, and uncaptured ranges separately.
3. For nonblocking submission, trace where values returned by Full/Closed go. If send().await or reserve().await is used, check whether that wait stops the next update. Also check for unbounded waiting in Promises or tasks after leaving the queue, and in retry destinations. Do not assume that finite memory can handle sustained overload without loss or stopping.
4. Before making changes, use finite input to reproduce normal operation, a short burst, insufficient capacity, save failure, a channel closed by the saving side, and a normal stop partway through input. Do not treat successful submission as save completion. Check that acceptance stops after failure, accepted items are drained or recovered, all send handles are released, the save task's result is checked, and flush/sync/commit conditions are met. Check whether shutdown handling runs even on an input exception or early return. Retain records with unknown outcomes, such as partial writes, as unknown.
5. Check what stopping can preserve. Retaining a local input file differs from requesting retransmission or retention of live input. State which input ID and which preceding state processing will resume from. Do not treat SDK pausing or history refetching as available without verification. Do not assume that the latest state alone can reconstruct conditions reached during a gap. Separate state recovery through historical replay from the conditions that permit current decisions to resume, and report freshness or deadline requirements as unknown if they are unknown. Do not unconditionally retry appends whose saving is unconfirmed and thereby create more duplicates or incomplete lines.
6. Implement the necessary minimal fix and rerun under the same conditions. Compare counts and IDs for processed, unprocessed, discarded, save-unconfirmed, and duplicate inputs, as well as decision results, save order, completion criteria, and exit codes. Avoid parallel saving that breaks required order or changes that discard unsaved records to finish. Report queue counts, bytes, the oldest wait, latency, CPU, and memory only where measured. Explicitly state if panic, process crash, forced termination, power loss, or shutdown deadlines have not been tested.
Finally, report the confirmed problems and evidence, minimal fixes, reproduction commands, whether every input is accounted for consistently in each scenario, and the remaining failure scope. Do not change areas that already meet the requirements. Zero locally discarded items alone does not guarantee that all items were saved, crash durability, gap-free reception of a real stream, or production correctness.Examine the separation of reception and decision processing from auxiliary saving in this repository, and verify that updates and records remain accounted for when the queue is full, saving fails, the writer closes, or processing ends normally. Make minimal fixes only for defects supported by evidence, and verify before and after using the same small local input.
Check the existing working rules, permissions, uncommitted changes, and versions of the language, runtime, SDK, and dependencies. Do not overwrite other changes, and limit modifications to the retention and shutdown conditions in this task. Production changes, load tests against external services, transaction submission, and paid contracts are outside scope. Proceed with the necessary local investigation, modifications, and replay checks. Do not output private keys, credentials, or customer data.
1. Identify the actual files and functions, the owner of received input, the updater of mutable state, queue capacity and the per-record byte limit, the number of writers, retries, and shutdown paths. Also investigate whether SDK callbacks wait for async processing to finish, whether processed counts mean save completion, and whether an upstream queue discards items when full. Separate confirmed facts, hypotheses, and unmeasured areas. If saving before a decision is required, preserve that dependency and do not treat the record as auxiliary.
2. Classify the same input IDs as unprocessed; decided, not accepted for saving; accepted, not written; accepted, save outcome unknown; or save complete. Verify that these five sets are disjoint and cover all input, and detect discards, duplicates, order violations, and double-counting. Do not arbitrarily classify records with unknown outcomes, such as partial writes, as successful or unwritten. Do not add the decided count on top of the five sets. Local sequence numbers assigned to a real stream identify the captured sequence; they are not proof that every server update was captured. Record disconnected, retransmitted, and uncaptured ranges separately.
3. For nonblocking submission, trace where values returned by Full/Closed go. If send().await or reserve().await is used, check whether that wait stops the next update. Also check for unbounded waiting in Promises or tasks after leaving the queue, and in retry destinations. Do not assume that finite memory can handle sustained overload without loss or stopping.
4. Before making changes, use finite input to reproduce normal operation, a short burst, insufficient capacity, save failure, a channel closed by the saving side, and a normal stop partway through input. Do not treat successful submission as save completion. Check that acceptance stops after failure, accepted items are drained or recovered, all send handles are released, the save task's result is checked, and flush/sync/commit conditions are met. Check whether shutdown handling runs even on an input exception or early return. Retain records with unknown outcomes, such as partial writes, as unknown.
5. Check what stopping can preserve. Retaining a local input file differs from requesting retransmission or retention of live input. State which input ID and which preceding state processing will resume from. Do not treat SDK pausing or history refetching as available without verification. Do not assume that the latest state alone can reconstruct conditions reached during a gap. Separate state recovery through historical replay from the conditions that permit current decisions to resume, and report freshness or deadline requirements as unknown if they are unknown. Do not unconditionally retry appends whose saving is unconfirmed and thereby create more duplicates or incomplete lines.
6. Implement the necessary minimal fix and rerun under the same conditions. Compare counts and IDs for processed, unprocessed, discarded, save-unconfirmed, and duplicate inputs, as well as decision results, save order, completion criteria, and exit codes. Avoid parallel saving that breaks required order or changes that discard unsaved records to finish. Report queue counts, bytes, the oldest wait, latency, CPU, and memory only where measured. Explicitly state if panic, process crash, forced termination, power loss, or shutdown deadlines have not been tested.
Finally, report the confirmed problems and evidence, minimal fixes, reproduction commands, whether every input is accounted for consistently in each scenario, and the remaining failure scope. Do not change areas that already meet the requirements. Zero locally discarded items alone does not guarantee that all items were saved, crash durability, gap-free reception of a real stream, or production correctness.The Japanese source versions of the two prompts published here were each copied in full by an AI separate from the implementer and applied to the TypeScript example and Rust price example in separate local copies. In each copy, the trial checked the eight TypeScript functional tests and six Rust functional tests in a release build, as well as the sequential and separated CLIs and failure scenarios. The target files, diagnosis of causes, reproduction commands, hashes of the original prompts, and results are recorded in the trial of wait diagnosis and separation and the trial of Full, failures, and shutdown.
No unnecessary changes were made to the separated versions, which already met the requirements. This educational material does not define acceptable data age, decision deadlines, or conditions for resuming current decisions after history recovery. Following the prompts, the trials reported these as undefined and unverified instead of inventing values. Retention checks in a local replay do not establish verification of resuming production decisions or real Geyser performance.
These AI trials check the specificity of the prompts and their consistency with the article. They are distinct from research demonstrating real readers' understanding, satisfaction, intention to return, or success rates in unknown repositories.
11. Turn Fast Data into Fast Responses
Even with a fast stream, unnecessary waits accumulated after reception delay the data's arrival at decision logic. Check what your implementation waits for and which order is necessary, then separate only the work that can progress independently. After separating saving, continue measuring CPU work, shared state, and queue waits, and refine the necessary boundaries one by one.
Once waits inside the application are reduced, examine data freshness before reception, RPC or stream access, network paths, and execution location as separate stages. Define the required response time, incoming volume, and stop and recovery conditions, then compare ERPC environments using the protocols, regions, times of day, and loads you will actually use. Choose fast data and an implementation that uses it efficiently to meet the same requirements.
References and Runnable Materials
-
[S01]
Arc::cloneadds an owner sharing the same heap allocation; it does not deeply copy the contents. Atomic reference-count operations have a cost, and Arc alone does not make concurrent mutation of inner values safe. https://doc.rust-lang.org/std/sync/struct.Arc.html -
[S02]
Sendis the property that allows ownership of a value to move between threads;Syncallows shared references to be used across threads. These are not themselves executors, locks, or ordering guarantees. https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -
[S03]
tokio::spawnregisters an asynchronous task with the executor. Ordinary spawn requires Send and static bounds on the future and output, and execution placement depends on runtime configuration. Unfinished tasks are not guaranteed to run to completion when the runtime shuts down. https://docs.rs/tokio/1.54.1/tokio/task/fn.spawn.html Distinguishing concurrency from parallelism and running tasks on a single thread: https://tokio.rs/tokio/tutorial/spawning -
[S04] A bounded Sender's
send().awaitwaits for capacity.try_sendreturns when full or when the receiver is closed. Successful sending does not mean reception or save completion. https://docs.rs/tokio/1.54.1/tokio/sync/mpsc/struct.Sender.html -
[S05]
TrySendError::Full(T)andClosed(T)return the unsent value. Ignoring the value without recovering it can lose a required record. https://docs.rs/tokio/1.54.1/tokio/sync/mpsc/error/enum.TrySendError.html -
[S06] After all Senders are dropped and the remaining queue is drained, recv returns None. Dropping the Receiver also drops unread values. The receiver can also be closed and then drained. https://docs.rs/tokio/1.54.1/tokio/sync/mpsc/index.html
-
[S07]
spawn_blockingmoves execution to a blocking pool. CPU work needs concurrency limits, and work queues after the limit is reached. Aborting work that has already started cannot be treated the same as aborting an ordinary async task. https://docs.rs/tokio/1.54.1/tokio/task/fn.spawn_blocking.html -
[S08] You can choose
current_threadormulti_thread.worker_threadssets the worker count for a multi-thread runtime; it does not mean pinning workers to CPU cores. https://docs.rs/tokio/1.54.1/tokio/runtime/struct.Builder.html -
[S09] Tokio File's flush completes pending writes, which differs from guaranteeing that OS buffers have been persisted to the device. sync_all/sync_data are separate operations. https://docs.rs/tokio/1.54.1/tokio/fs/struct.File.html
-
[S10] write_all and flush are separate AsyncWriteExt methods. Do not omit error and cancellation handling. https://docs.rs/tokio/1.54.1/tokio/io/trait.AsyncWriteExt.html
-
[S11] Shared state in Tokio can be handled with brief locks or a state-owning task and message passing. Consider a design that does not hold a lock across await. https://tokio.rs/tokio/tutorial/shared-state
-
[S12] Node's asynchronous fs APIs run outside the event loop, but do not guarantee automatic ordering of multiple changes to the same file. Avoid changes that overlap writes without waiting. sync is a separate persistence request. https://nodejs.org/api/fs.html
-
[S13] Node worker_threads can execute JavaScript CPU work in parallel. Built-in async I/O is suitable for I/O, and CPU work is also normally controlled through a worker pool. https://nodejs.org/api/worker_threads.html
-
[S14] Distinguish work that occupies the CPU for a long time from asynchronous I/O waits in Node. https://nodejs.org/learn/asynchronous-work/dont-block-the-event-loop
-
[S15] Python asyncio.Queue(maxsize>0) sets a capacity; put waits when full, and put_nowait raises QueueFull. asyncio.Queue is not thread-safe. https://docs.python.org/3/library/asyncio-queue.html
-
[S16] Python also supports concurrency through asyncio tasks. CPU parallelism with to_thread depends on the GIL, implementation, and extension modules. https://docs.python.org/3/library/asyncio-task.html
-
[S17] Python provides thread, interpreter, and process executors. Control worker counts separately from the amount of work waiting for execution. https://docs.python.org/3/library/concurrent.futures.html
-
[S21] Node EventEmitter listener invocation and the handling of async listeners' Promises and rejections. Event emission and completion of a Promise returned by a listener are handled separately. https://nodejs.org/api/events.html
-
[S22] Rust ownership and passing values to functions. After a non-Copy value is moved, the original variable cannot continue to be used as its owner. Returned values can be received by the caller. https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html
-
[S24] The Solana Stream SDK's TypeScript Geyser runner:
runHandlerdoes not await Promises; full-queue drops and the point where processed counts are recorded. Source inspection pinned to a commit. https://github.com/ValidatorsDAO/solana-stream/blob/3b22307033ec6d7b78242d3b4cc9f3168209dcfd/client/geyser-ts/src/lib/geyserRunner.ts -
[S25] The same SDK's Rust Geyser runner: the
stream.next()reception entry point,try_send, discarding Update on Full, and handling disconnection events. https://github.com/ValidatorsDAO/solana-stream/blob/3b22307033ec6d7b78242d3b4cc9f3168209dcfd/client/geyser-rs/src/runtime/runner.rs -
SDK source audit and measurement boundaries: sdk-stream-entry-audit.md.
-
[L03] The six-input TypeScript example in the main article. Implementation, decisions, order, saved bytes, and gate-based checks of Full/Closed/failure/shutdown: example.ts, execution instructions and verification results, and check code.
-
[S30] Tokio Semaphore: acquiring and releasing capacity, owned permits, and waking waiters on close. Distinguish Arc's shared ownership from the synchronization mechanism. https://docs.rs/tokio/1.54.1/tokio/sync/struct.Semaphore.html
-
[L04] Complete Rust Geyser replay example and functional checks: src/replay.rs, execution instructions, and functional-check record. Synthetic input verifies ownership handoff, processing results, order, Full, failures, and shutdown. Detailed verification conditions are in the validation notes.
-
[S34] Awaiting JoinHandle returns the task's output or a JoinError. Merely dropping the handle detaches the task; it does not confirm completion. https://docs.rs/tokio/1.54.1/tokio/task/struct.JoinHandle.html
-
[L06] Rust/Tokio example with the same six prices: implementation, execution instructions, and functional-check code. A release build verifies decisions, order, JSONL bytes, Full, Closed, failures, stopping, and retention across the five categories. Language speed rankings and real Geyser performance have not been measured.
-
ERPC: https://erpc.global/en/
-
Validators DAO official Discord: https://discord.gg/C7ZQSrCkYR
-
Primary-source mapping: technical sources and verified points












