Await One Public Request
A socket can carry several requests before any reply arrives. If the application resolves whichever promise was created first, an out-of-order reply can complete the wrong operation. Request IDs let the client associate each response with the command that created it.
A subscription has a different lifetime. Its market or account events continue arriving after the subscribe response. Awaiting the subscription does not turn those later events into a single result.
The Binance SDK tutorial includes the promise client. This example asks for Spot server time and closes its connection:
server-time.mjs
import { WebsocketAPIClient } from 'binance';
const client = new WebsocketAPIClient();
try {
const response = await client.getSpotServerTime();
console.log(response);
} finally {
await client.disconnectAll();
}
The client associates the reply with that request. Continuous market-data handling still uses the stream client and its message events. Available request methods depend on the exchange API; a stream-only endpoint cannot gain order entry by wrapping it in a promise.
Keep Reply and Execution Separate
For an order command, the reply can establish that the request was accepted or rejected. A fill may occur later, or its private event may arrive before the reply. The matching promise does not establish the order's final executed quantity.
Persist the Order Intent and supported client order ID before sending a command. Associate the reply and later account events with that identity. Order-state handling must tolerate either arrival order.
Handle a Missing Reply
Suppose a request reaches the exchange and the socket disconnects before its reply returns. The local promise can reject while the exchange accepts the command. That rejection establishes a local communication failure; it does not establish rejection by the exchange.
After recovery, query the order by the available identifiers and retain an unknown result if the lookup is inconclusive. Sending another placement immediately can create a second order. A local timeout implemented with Promise.race has the same limitation: it does not cancel a request already being processed remotely.
Measure the Actual Path
A persistent connection avoids some connection setup work. REST can also reuse connections. Which path has lower latency depends on client configuration, network conditions, endpoint processing, and load.
Measure from dispatch to the relevant reply, then measure the separate delay to the account event required by the application. Comparing an HTTP acknowledgement with a WebSocket fill would compare different events.
Related articles
Continue from here