# Asynchronous communication

_This page explains how to send asynchronous interprocess communication (IPC) messages in q: flushing the outbound queue, broadcasting to several clients, writing asynchronous callbacks, and blocking on a handle for an expected reply._

An asynchronous request sends a message and returns immediately, without waiting for a response. It suits high-throughput work such as logging and data publishing, and any command whose result you do not need.

To send a message asynchronously, apply it to a **negative** connection handle, which you get by applying [`neg`](../../ref/neg.md) to the handle:
```q
q)neg[h]"a:10"                            / tell the server to create a variable 'a'
q)neg[h]("0N!"; "hello from client")       / tell the server to print to its console
```

Because the client never waits for a response, asynchronous messaging is essential in systems such as tickerplants, where blocking on a slow subscriber would stall every other subscriber.

> **Tip — Size socket buffers for the connection count you expect**
>
>
> Increasing the [TCP send and receive buffer sizes](../performance/os.html#socket-buffers-for-ingestion) in your operating system can improve throughput on a busy connection.
>
> The operating system reserves that buffer memory per socket, whether or not the socket is busy. Scaling the buffers up across thousands of concurrent connections depletes system memory rather than improving throughput, so size them for the number of connections you expect, not for the busiest one.
>
## Flush the message queue

An asynchronous message optimizes for unblocking the sender, not for request latency. By default q buffers the message in user space and writes it to the socket in its own time. An _async flush_ hands the serialized bytes for a handle to the kernel immediately:
```q
q)neg[h][]     / flush every pending async message on handle h
q)neg[h](::)   / the same thing
```

To inspect the size of the outbound queue, use [`.z.W`](../../ref/dotz.md#zw-handles) for every handle, or [`-38!x`](../../ref/internal.md#-38x-socket-table) for one handle.

> **Tip — A synchronous message flushes the queue and confirms delivery**
>
>
> Sending any synchronous message on the same handle, such as `h""`, also flushes the asynchronous queue. Because the remote process handles messages in order, a response to that synchronous message confirms that it has processed every asynchronous message you sent before it.
>
## Broadcast a message

To send one message to several clients, use _async broadcast_, [`-25!`](../../ref/internal.md#-25x-async-broadcast). It serializes the message once, which makes it more efficient than sending to each client in a loop.
```q
q)(h1; h2; h3): hopen each `::5000`::5001`::5002   / handles for three clients
q)msg: (`someFunction; `arg1; `arg2)
q)-25!((h1; h2; h3); msg)                          / serialize once, send to all three
```

## Asynchronous callbacks

An asynchronous callback lets a client send a request without blocking and still receive the result once the server has it: the server replies by making its own asynchronous call back to a function that the client named in the request. Because neither the request nor the reply blocks, the client can do other work while it waits, and one client's slow or unresponsive callback cannot stall the server's replies to anyone else.

The pattern has three parts: the client's call, the server function's signature, and the server's callback.

1. **The client's call.** The client sends an asynchronous request to a named function on the server. Its last argument is a symbol naming a function that exists on the client.
    ```q
    / (neg h) (`remoteFunc; arg1; ..; argN; `clientCallback)
    (neg h) (`proc; 42; `clientFunc)
    ```

2. **The server function's signature.** Define the remote function to take the callback's name as its final parameter.
    ```q
    / remoteFunc: {[arg1; ..; argN; callbackName] ... }
    proc: {[dataArg; callbackName] ... }
    ```

3. **The server's callback.** Inside the remote function, [`.z.w`](../../ref/dotz.md#zw-handle) gives the handle of the calling process. Use it to call the client's named function asynchronously, passing the result.
    ```q
    proc: {[dataArg; callbackName]
      result: dataArg * 2;               / do the work
      h: .z.w;                           / the caller's handle
      (neg h) (callbackName; result);    / call back asynchronously
    }
    ```

Two details make this work. Read [`.z.w`](../../ref/dotz.md#zw-handle) inside the server function, where it names the calling connection; and make the callback asynchronous (`neg h`), so that neither side blocks.

The examples below use [`0N!`](../../ref/display.md) to print to the console of whichever process runs it.

### A single argument and a callback

A client calls a remote function with one argument and names a callback to receive the result.

On the server, define `proc` to take a data argument `x` and a callback name `y`. It does its work, then uses the caller's handle to invoke the callback:
```q
\p 5000                                        / listen on port 5000
serverFunc: {0N!x;}                            / stands in for the real server logic
proc: {serverFunc x; h: .z.w; (neg h) (y; 43)} / the function the client calls
```

On the client, define the callback, open a handle, and call `proc` asynchronously:
```q
clientFunc: {0N!x;}   / receives the result
h: hopen `::5000
(neg h) (`proc; 42; `clientFunc)
```

The server console shows `42`, and the client console then shows `43`.

### Several arguments

To call a remote function with more than one data argument, pass them as a list.

On the server, define `proc3` to take a list of arguments `x` and a callback name `y`. It uses [Apply](../../ref/apply.md) (`.`) to spread the list across the parameters of `add3`:
```q
\p 5000
add3: {x+y+z}                                  / takes three arguments
proc3: {r: add3 . x; 0N!r; (neg .z.w) (y; r)}  / unpacks the list, then calls back
```

On the client, send the arguments as a single list:
```q
clientFunc: {0N!x;}
h: hopen `::5000
(neg h) (`proc3; 1 2 3; `clientFunc)
```

The server console shows `6`, and the client console then shows `6`.

### A generic dispatcher

Rather than write a wrapper for every server-side function, define one generic wrapper, `dispatcher`. A client can then call any server-side function without new code on the server.

On the server, `dispatcher` takes the target function's name, its arguments as a list, and the client's callback name. It resolves the name, applies the arguments, and calls back with the result:
```q
\p 5000
add3: {x+y+z}                                 / an arbitrary server function
dispatcher: {(neg .z.w) (z; (value x) . y)}   / runs any function of any rank
```

On the client, name the target function, its arguments, and the callback:
```q
clientFunc: {0N!x;}
h: hopen `::5000
(neg h) (`dispatcher; `add3; 1 2 3; `clientFunc)
```

The client console shows `6`. The server does the arithmetic but prints nothing.

### An anonymous function

Send a function literal from the client to run on the server. This needs no predefined function on the server at all.

On the server, start a q process listening on a port, with no definitions:
```bash
q -p 5000
```

On the client, send an anonymous function that carries both the work and the callback:
```q
q)clientFunc: {0N!x;}
q)h: hopen `::5000
q)(neg h) ({(neg .z.w) (z; x*y)}; 6; 7; `clientFunc)
42
```

The message carries the anonymous function `{(neg .z.w) (z; x*y)}`, its arguments `6` and `7`, and the callback name `` `clientFunc ``. The server computes `6*7` and the client console shows `42`.

> **Warning — An unprotected server runs whatever a client sends**
>
>
> Treat this pattern with great care outside a trusted network. A server that evaluates arbitrary client input is open to arbitrary code execution by any client that can connect. Restrict [which functions a client can run](security.md#authentication-and-authorization) before you expose such a server.
>
## Blocking async { #blocking-async }

The point of an asynchronous message is that the sender does not wait. Sometimes, though, you want to send asynchronously and then block for a specific reply. To block until the next asynchronous message arrives on handle `h`, call `h[]`.

This pattern is infrequent, and worth reaching for only in the two situations below: consuming an asynchronous interface as though it were synchronous, and starting remote work on several processes before you collect any of the results.

> **Note — Also called _deferred synchronous_**
>
>
> Older material calls this pattern _deferred synchronous_, a name worth treating with care: the reply is not deferred, and nothing about the exchange is synchronous. Both messages are ordinary asynchronous messages; the only synchronous thing is that the sender chooses to block. [Deferred response](deferred-response.md) is a separate mechanism with a confusingly similar name — it suspends a genuinely synchronous reply with `-30!`.
>
### Consume an asynchronous interface synchronously

Suppose a server offers a function you can't change, which returns its result through an asynchronous callback, and you need that result inside the function you are writing rather than in a callback that runs after your function has exited.

On the server:
```q
\p 5000

/ Computes a result and sends it back to the calling client (.z.w)
/ asynchronously. Assume you cannot modify this function.
asyncAdd: {neg[.z.w] (`setAddResult; x+y)}
```

On the client:
```q
q)h: hopen `::5000
q){
    neg[h](`asyncAdd; 40; 1);   / send the async request, expecting 41
    (`setAddResult; res): h[];  / block for the reply, whose shape you know
    res+1
    }[]
42
```

The assignment `` (`setAddResult; res): h[] `` is a [list pattern](../../ref/pattern.md#list): it checks that the reply starts with the expected symbol and binds the payload to `res` in one step, so an unexpected message raises an error instead of being silently misread.

### Start remote work, then collect the results

To overlap remote work with local work, send every request first, flush each handle, do your local work, and only then block for the replies.

On both servers:
```q
\p 5000   / and \p 5001 on the second process

/ Runs a query and sends the result back to the original client asynchronously
asyncWrap: {neg[.z.w] (`asyncWrapResult; value x)}
asyncAdd: {neg[.z.w] (`setAddResult; x+y)}
```

On the client:
```q
q)(h1; h2): hopen each `::5000`::5001
q){
    neg[h1](`asyncWrap; (+; 10; 10));   / start remote work on the first server
    neg[h1][];                          / flush, or the message sits in the queue
    neg[h2](`asyncAdd; 10; 10);         / start remote work on the second server
    neg[h2][];

    two: 1+1;                           / local work, overlapping the remote work

    (`asyncWrapResult; res1): h1[];     / now collect the results
    (`setAddResult; res2): h2[];

    res1+res2+two
    }[]
42
```

Flushing matters here. Without `neg[h1][]` and `neg[h2][]`, q would send the requests only when you reach `h1[]` and `h2[]`, which defeats the purpose of starting them early.

### Limits of blocking on a handle

`h[]` returns the next asynchronous message on the handle, whatever it is. That makes the pattern unsafe on a handle that also carries unsolicited asynchronous traffic.

On the server:
```q
\p 5000
asyncAdd: {neg[.z.w] (`setAddResult; x+y)}

\t 10                                    / every 10 ms, send an unrelated message
.z.ts: {neg[key .z.W]@\: (abs; -42)}
```

On the client, the pattern works until an unrelated message arrives first:
```q
q)while[1; neg[h](`asyncAdd; 10; 10); (`setAddResult; res): 0N!h[]]
(`setAddResult;20)
(`setAddResult;20)
(abs;-42)                                / not the message the pattern expects
'match
    [0]  while[1; neg[h](`asyncAdd; 10; 10); (`setAddResult; res): 0N!h[]]
                                              ^
```

Incoming **synchronous** queries don't interfere, because `h[]` serves them behind the scenes and keeps waiting for the first asynchronous message. Their side effects still reach your process, though, which can surprise code that doesn't expect them:
```q
/ On the server: send a sync query with a side effect, frequently
\t 10
.z.ts: {key[.z.W]@\: (0N!; -42)}
```
```q
/ On the client: the expected results still arrive, interleaved with the
/ output of the sync queries that h[] ran on your behalf
q)while[1; neg[h](`asyncAdd; 10; 10); (`setAddResult; res): 0N!h[]]
(`setAddResult;20)
-42                                      / printed by the sync query h[] ran
(`setAddResult;20)
```

## Deadlocks

As already demonstrated, incoming sync requests are executed when the process is waiting for an async message by `handle[]`.
Also, both incoming sync and async requests are executed when waiting for the result of a sync query!

On the server:
```q
q)add:{h:.z.w;
       neg[h]({-1"<- async msg"};(::));
       forty:h({-1"<- sync query";x};40);
       forty+x+y}
```

On the client:
```q
q){-1"-> querying h...";res:h (`add;1;1);-1"<- querying h returned";res}[]
-> querying h...
<- async msg
<- sync query
<- querying h returned
42
```

Therefore, it is not possible to deadlock with just two processes exchanging sync queries and async messages!

However, there is a 3rd IPC action that potentially blocks: the async flush. When flushing large amounts of outgoing data to a handle
when the receiving party is not cooperating with the reception, the sender will block. With both parties doing the same, it's a deadlock.

Both processes:
```q
q)neg[h] til 1000000000;neg[h][] /deadlock
```

Interestingly, with q IPC between two processes, the cause of a deadlock is not the reception of a message nobody wants to send, but rather the sending of messages nobody wants to receive!

Note that it's flushing that causes the problem. Without flush, you can safely send any amount of data. (If the receiver isn't cooperating, the sender will eat all RAM, but no deadlock.)

Also note that when sending an sync query, the process must first actually send the query message to the peer, therefore every sync query inherently involves a flush behind the scenes.
Therefore, two processes can deadlock if they mix sending large amounts of data and synchrous requests.

Both processes:
```q
q)neg[h]til 1000000000;h"1+2" /deadlock
```

Also, simply sending a large sync request can deadlock:

Both processes:
```q
q)h(neg;til 1000000000) /deadlock
```

So we can conclude that when only two processes communicate, deadlocks can only happen if there are large messages involved.
However, when there are three or more processes, a deadlock is much easier to achieve. When multiple processes send syncronous queries or blocking async's (or a mixture of the two),
a directed circle is a deadlock: e.g. P1 querying P2, P2 querying P3 and P3 querying P1 -- regardless of message sizes.
To design a guaranteed deadlock-free group of interconnected processes, do not allow directed circles, i.e. make the communication pattern a DAG (Directed Acyclic Graph).

## The main event loop { #the-main-event-loop }

What we discussed so far is more than enough for solving most IPC tasks.
However, to fully understand q IPC, you must know how the main event loop of q works.

The q process is single-threaded. It runs one piece of code at a time. It alternates between two kinds of code: q code and C code. The C code sends and receives the data of IPC messages. It also selects the next piece of q code to run. This pseudocode shows the event loop:
```c
while(!exit){
  select(fds,timer)
  if(timerExpired)
    execute timer action;
  else{
    for(fds ready to write) write as much as that socket accepts
    for(fds ready to read) read, and process if a msg is received in full, up to one msg per socket
  }
}
```

Note these points:

- `select` waits until a timer expires or a socket is ready. The `timer` argument is the time to the next timer tick.
- If the timer expired, the loop runs [`.z.ts`](../../ref/dotz.md#zts-timer) and does no socket work in that iteration.
- Otherwise, the loop first writes to each socket that is ready to write. It writes only the bytes that the socket accepts without blocking. The rest stays in the outgoing queue of q.
- Then the loop reads from each socket that is ready to read. It processes a message only when the message is received in full. It processes at most one message for each socket in one iteration.
- Processing a message means executing the associated q code ([`.z.po`](../../ref/dotz.md#zpo-open), [`.z.pg`](../../ref/dotz.md#zpg-get), [`.z.ps`](../../ref/dotz.md#zps-set)). The q function is fully executed in one go, never preempted.
- A new connection is a read event on the listening socket.

The loop does only one task at a time. While a handler q function is executed, the loop cannot do any other task. During this time, the process:

- does not read new messages
- does not run other handlers
- does not write the bytes that remain in the outgoing queue

A long-running handler therefore delays every other data flow, including the sending of replies that are already in the queue.

A process can also wait inside a handler. These are the cases:

- A sync query, such as `h"query"`, first sends the request fully, which itself can wait if the message is large. Then it waits for the reply. During this second phase, the process runs incoming sync and async messages *on that specific handle only*.
- A blocking async call, `h[]`, waits for one async message. During this time, the process executes incoming sync messages, *on that specific handle only*.

## Large sync responses may also need flushing { #response-flush }

When a sync call returns, the message is not always fully on the wire.

Assume that q sends a message and you do not flush the handle. Then q does these steps:

1. q serializes the message.
2. q writes the bytes that the socket accepts.
3. If the message is large, the send buffer of the kernel becomes full. q keeps the remaining bytes in the outgoing queue, in user space.
4. The remaining bytes are only sent in the write phase of [the event loop](#the-main-event-loop).

While the process executes q code, data waiting in the outgoing queue is not sent, not even if the kernel socket buffer of a connection has been emptied. The write continues only in the next iteration of the event loop.

This applies to all outgoing messages, including the replies to synchronous queries. The function returns the result. Then q sends the result as the reply message. If the message is large, q sends only a part of it. The rest is only queued.

After the sync query finishes, the loop can select other work immediately. This happens if a complete IPC message is waiting or the timer expires. q sends the rest of the sync reply later, as for any other outgoing data. The client must wait for the rest of the reply, indefinitely.

In this example, a server has two clients. Client A calls `bigReply`. Client B calls `longJob`. On the server:
```q
q)bigReply:{[x] til 100000000}   / large result, returned to the caller
q)longJob:{system"sleep 600"}     / long-running work
```

On client A:
```q
q)hA(`bigReply;::)               / sync call, blocks until the whole reply has arrived
```

On client B, at about the same time:
```q
q)neg[hB](`longJob;::)           / sync or async call, both have the same effect
```

If the request from client B arrives first, obviously the request of A will have to wait 10 minutes before it is executed.
However, if the message from client A arrives first, if it is quickly followed by request B -- before the whole reply of A is on the wire -- client A will have to wait for B to finish, in spite it arrived first! Worse, A might have to wait for several other subsequent queries!

### Reply latency is unpredictable

A single server that serves many IPC clients will always have this problem. Several servers that share a listening port (socket sharding) have the same problem: The time that a client waits for a reply depends not only on the queries that arrived before. If the reply is large, the waiting also depends on the queries that arrive after!

Another reason why a properly implemented [loadbalancer](../interact_with_databases/concurrency.html#a-protocol-aware-load-balancer-the-fastest-option) is critical in any multi-user system.

### Asynchronous and deferred messages

For a large asynchronous message, the handle can be flushed after sending the message. The same can be done for the response to a [deferred synchronous request](deferred-response.md). For more information, refer to [Flush the message queue](#flush-the-message-queue).
```q
q)neg[h](`callback; bigResult)
q)neg[h][]                      / hand the queued bytes to the kernel now
```

### Ordinary synchronous responses

For an ordinary synchronous query, you cannot flush the reply. q sends the reply after your function returns. Your code cannot flush at that time.

You have these options:

- **Keep other work short.** Make timer functions and other handlers short. Split long jobs into small steps. Then the process returns quickly to the event loop.
- **Reduce the size of the reply.** Return only the columns and rows that the client needs. You can also [compress](../../ref/set.md#compression) the data.
- **Defer the response.** Use [`-30!`](deferred-response.md) to keep the synchronous reply open. Then send the reply with `-30!(handle;isError;result)`. Flush the handle with `neg[handle][]`. With this method, you control when q sends the reply.
- **Use a loadbalancer.**

> **Warning — No simple solution for plain synchronous queries**
>
>
>
## Next steps

- [IPC basics](basics.md) — open and close connections and send synchronous requests.
- [Defer synchronous responses](deferred-response.md) — hold a synchronous reply open with `-30!`, so that a gateway can fan a query out asynchronously and answer once.
- [Configure listening ports](listening-port.md) — service names, ephemeral and ranged ports, multi-threaded input mode, load balancing, and Unix domain sockets.
- [Secure and monitor IPC connections](security.md) — restrict what a client can run, and track and interrupt connections.
- [A load-balancing q server](../manage_streaming_data/load-balancing.md) — blocking on a handle in a worked implementation.
