Programming Search⌘K

Patternadvanced

Asynchronous Completion Token

Also called ACT, completion token, active demultiplexing.

An asynchronous completion token is a value that a client sends with each asynchronous request and that the service returns unchanged, so the client can match each reply to its request.

Family
concurrency
Intent
Send a token with each asynchronous operation, and use the token that comes back with the completion to find the state and the action for that operation.
Also called
Active Demultiplexing

Intent

The Asynchronous Completion Token design pattern efficiently dispatches processing actions within a client in response to the completion of asynchronous operations invoked by the client.1 It is also known as Active Demultiplexing.1

Problem

When a client invokes an operation request asynchronously on one or more services, each service indicates its completion by sending a response back to the client.1 The replies can come in any order. The client must know, for each reply, which request it answers and what to do next. If the client parses the reply or searches a list to find that out, each completion costs time, and the client code grows.

Solution

For every asynchronous operation that a client invokes on a service, create an asynchronous completion token (ACT) that uniquely identifies the actions and state necessary to process the operation's completion, and pass the ACT along with the operation to the service.1 When the service replies to the client, its response must include the ACT that was sent originally.1

The participants are a service, a client, the token and the completion handler.1 For a client, an ACT can be an index into a table or a direct pointer to memory. To the service, however, the ACT is simply an opaque value that it returns unchanged.1

client                          service
  token = new id; table[token] = (state, action)
  request(data, token) ------->
                                 ... work, in any order ...
  <------------------------------ reply(result, token)
  (state, action) = table.pop(token)
  action(state, result)

Example

The example files show one program in each language. The client sends two load requests, each with a numeric token, and keeps a table from token to image name. The service answers in the reverse order. The client finds each image by its token, not by the order of the replies. The program prints:

send 1: load image-7
send 2: load image-9
done 2: image-9 loaded
done 1: image-7 loaded
PythonGitHub
def service(requests):
    # replies in the reverse order; the token comes back unchanged
    return [(token, f"{name} loaded") for token, name in reversed(requests)]


pending = {}  # token -> state that the completion needs
requests = []
for token, name in enumerate(["image-7", "image-9"], start=1):
    pending[token] = name
    requests.append((token, name))
    print(f"send {token}: load {name}")

for token, result in service(requests):
    name = pending.pop(token)  # the token finds the state at once
    print(f"done {token}: {result}")
Output
send 1: load image-7
send 2: load image-9
done 2: image-9 loaded
done 1: image-7 loaded
  • Verdict: idiom. The token is an integer key into a dictionary of pending operations. A future from concurrent.futures can take the place of the integer.
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>

using Request = std::pair<int, std::string>;

std::vector<Request> service(const std::vector<Request>& requests) {
    std::vector<Request> replies;
    for (auto it = requests.rbegin(); it != requests.rend(); ++it) {  // reverse order
        replies.push_back({it->first, it->second + " loaded"});
    }
    return replies;
}

int main() {
    std::map<int, std::string> pending;
    std::vector<Request> requests;
    const std::vector<std::string> names{"image-7", "image-9"};
    for (std::size_t i = 0; i < names.size(); ++i) {
        int token = static_cast<int>(i) + 1;
        pending[token] = names[i];
        requests.push_back({token, names[i]});
        std::cout << "send " << token << ": load " << names[i] << "\n";
    }
    for (const auto& [token, result] : service(requests)) {
        pending.erase(token);  // the token finds the state at once
        std::cout << "done " << token << ": " << result << "\n";
    }
}
Output
send 1: load image-7
send 2: load image-9
done 2: image-9 loaded
done 1: image-7 loaded
  • Verdict: idiom. The token here is an integer key. A C or C++ program can also use a pointer to the state as the token.
JavaGitHub
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    record Request(int token, String name) {}
    record Reply(int token, String result) {}

    static List<Reply> service(List<Request> requests) {
        List<Reply> replies = new ArrayList<>();
        for (Request r : requests) replies.add(new Reply(r.token(), r.name() + " loaded"));
        Collections.reverse(replies);  // replies in the reverse order
        return replies;
    }

    public static void main(String[] args) {
        Map<Integer, String> pending = new HashMap<>();
        List<Request> requests = new ArrayList<>();
        String[] names = {"image-7", "image-9"};
        for (int i = 0; i < names.length; i++) {
            int token = i + 1;
            pending.put(token, names[i]);
            requests.add(new Request(token, names[i]));
            System.out.println("send " + token + ": load " + names[i]);
        }
        for (Reply reply : service(requests)) {
            pending.remove(reply.token());  // the token finds the state at once
            System.out.println("done " + reply.token() + ": " + reply.result());
        }
    }
}
Output
send 1: load image-7
send 2: load image-9
done 2: image-9 loaded
done 1: image-7 loaded
  • Verdict: idiom. Records carry the token in the request and in the reply, and a HashMap holds the pending state.
using System;
using System.Collections.Generic;
using System.Linq;

static class Program
{
    static IEnumerable<(int Token, string Result)> Service(List<(int Token, string Name)> requests) =>
        requests.AsEnumerable().Reverse().Select(r => (r.Token, r.Name + " loaded"));

    static void Main()
    {
        var pending = new Dictionary<int, string>();
        var requests = new List<(int Token, string Name)>();
        string[] names = { "image-7", "image-9" };
        for (int i = 0; i < names.Length; i++)
        {
            int token = i + 1;
            pending[token] = names[i];
            requests.Add((token, names[i]));
            Console.WriteLine($"send {token}: load {names[i]}");
        }
        foreach (var (token, result) in Service(requests))
        {
            pending.Remove(token); // the token finds the state at once
            Console.WriteLine($"done {token}: {result}");
        }
    }
}
Output
send 1: load image-7
send 2: load image-9
done 2: image-9 loaded
done 1: image-7 loaded
  • Verdict: idiom. Named tuples carry the token, and a Dictionary<int, string> holds the pending state.
JavaScriptGitHub
function service(requests) {
  // replies in the reverse order; the token comes back unchanged
  return [...requests].reverse().map(([token, name]) => [token, `${name} loaded`]);
}

const pending = new Map(); // token -> state that the completion needs
const requests = [];
["image-7", "image-9"].forEach((name, i) => {
  const token = i + 1;
  pending.set(token, name);
  requests.push([token, name]);
  console.log(`send ${token}: load ${name}`);
});

for (const [token, result] of service(requests)) {
  pending.delete(token); // the token finds the state at once
  console.log(`done ${token}: ${result}`);
}
Output
send 1: load image-7
send 2: load image-9
done 2: image-9 loaded
done 1: image-7 loaded
  • Verdict: idiom. The token is a number key in a Map. With promises, each call returns its own promise, which plays the part of the token.
TypeScriptGitHub
type Token = number;
type Request = [Token, string];

function service(requests: Request[]): Array<[Token, string]> {
  // replies in the reverse order; the token comes back unchanged
  return [...requests].reverse().map(([token, name]): [Token, string] => [token, `${name} loaded`]);
}

const pending = new Map<Token, string>();
const requests: Request[] = [];
["image-7", "image-9"].forEach((name, i) => {
  const token: Token = i + 1;
  pending.set(token, name);
  requests.push([token, name]);
  console.log(`send ${token}: load ${name}`);
});

for (const [token, result] of service(requests)) {
  pending.delete(token);
  console.log(`done ${token}: ${result}`);
}
Output
send 1: load image-7
send 2: load image-9
done 2: image-9 loaded
done 1: image-7 loaded
  • Verdict: idiom. The alias Token names the role of the number, and the map type fixes what the client stores for each token.
package main

import "fmt"

type request struct {
	token int
	name  string
}

func service(requests []request) []request {
	replies := make([]request, 0, len(requests))
	for i := len(requests) - 1; i >= 0; i-- { // reverse order
		replies = append(replies, request{requests[i].token, requests[i].name + " loaded"})
	}
	return replies
}

func main() {
	pending := map[int]string{}
	var requests []request
	for i, name := range []string{"image-7", "image-9"} {
		token := i + 1
		pending[token] = name
		requests = append(requests, request{token, name})
		fmt.Printf("send %d: load %s\n", token, name)
	}
	for _, reply := range service(requests) {
		delete(pending, reply.token) // the token finds the state at once
		fmt.Printf("done %d: %s\n", reply.token, reply.name)
	}
}
Output
send 1: load image-7
send 2: load image-9
done 2: image-9 loaded
done 1: image-7 loaded
  • Verdict: idiom. A struct carries the token, and a map holds the pending state.
RustGitHub
use std::collections::HashMap;

fn service(requests: &[(u32, String)]) -> Vec<(u32, String)> {
    // replies in the reverse order; the token comes back unchanged
    requests.iter().rev().map(|(t, n)| (*t, format!("{} loaded", n))).collect()
}

fn main() {
    let mut pending: HashMap<u32, String> = HashMap::new();
    let mut requests = Vec::new();
    for (i, name) in ["image-7", "image-9"].iter().enumerate() {
        let token = i as u32 + 1;
        pending.insert(token, name.to_string());
        requests.push((token, name.to_string()));
        println!("send {}: load {}", token, name);
    }
    for (token, result) in service(&requests) {
        pending.remove(&token); // the token finds the state at once
        println!("done {}: {}", token, result);
    }
}
Output
send 1: load image-7
send 2: load image-9
done 2: image-9 loaded
done 1: image-7 loaded
  • Verdict: idiom. The token is a u32 key.

Consequences

Benefits:1

  • Simpler client data structures. The ACT returned by the service contains all the information needed to demultiplex to the appropriate client completion action.1
  • Efficient state acquisition. ACTs can be used as indices or pointers to operation state for highly efficient access, thereby eliminating costly table searches.1
  • Space efficiency. In C and C++, ACTs that are four byte void pointers can reference arbitrarily large objects.1
  • No fixed concurrency policy. Clients can be single-threaded or multithreaded, depending on application requirements.1

Liabilities:1

  • Memory leaks. They can result if clients use ACTs as pointers to dynamically allocated memory and services fail to return the ACTs.1
  • Re-mapping. If ACTs are used as direct pointers to memory, errors can occur if part of the application is re-mapped in virtual memory.1
  • Authentication. The client may need to authenticate the ACT before using it, if the server cannot be trusted to have treated the ACT opaquely.1

Without a token, a client often matches replies to requests by their order. That works only while the service keeps the order:

This code runs but gives a wrong answer on purpose.

pending = ["image-7", "image-9"]  # names in the order of the requests
replies = ["data of image-9", "data of image-7"]  # the service answers out of order

for reply in replies:
    name = pending.pop(0)  # assumes the first reply answers the first request
    print(name, "<-", reply)
Output
image-7 <- data of image-9
image-9 <- data of image-7

When not to use it

  • The calls are synchronous. The caller then waits for each reply, and the call stack already holds the state.
  • The service keeps a strict order, and the protocol says so. A counter of replies is then enough.
  • The language gives a future or a promise for each call. The future is then the token, and the program does not need its own table.
  • Index or pointer. The token can be an index into a table of pending operations, or a pointer to the state.1 An index can be checked; a pointer is faster but can dangle.
  • Memento. The Asynchronous Completion Token and Memento patterns are similar with respect to the participants: in both, one object holds a value that it treats as opaque.1
  • Proactor. The completion handlers of a Proactor often use tokens. POSA2 puts both in its event handling patterns.2
  • Futures as tokens. In Python, as_completed yields futures as they complete.3 The documentation example marks each future with its URL in a dictionary, and the future is the key that finds the state again:
import concurrent.futures
import time


def load(name, delay):
    time.sleep(delay)
    return f"{name} loaded"


jobs = {"image-7": 0.2, "image-9": 0.0}  # image-9 finishes first
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
    future_to_name = {pool.submit(load, n, d): n for n, d in jobs.items()}
    for future in concurrent.futures.as_completed(future_to_name):
        name = future_to_name[future]  # the future is the token
        print(name, "->", future.result())
Output
image-9 -> image-9 loaded
image-7 -> image-7 loaded

Known uses

  • Operating system asynchronous I/O. The pattern is used by most operating systems that support asynchronous I/O, such as Windows NT I/O completion ports and the POSIX Asynchronous I/O API.1
  • Linux io_uring. The user_data field of a request is custom data that is passed unchanged from submission to completion.4
  • CORBA. The TAO CORBA Object Request Broker uses the pattern to demultiplex various types of requests and responses.1
  • FedEx. The sender of a package uses the internal billing reference field of the Airbill as an ACT, and FedEx returns it with the invoice.1

References

  1. Douglas C. Schmidt, Asynchronous Completion Token (POSA2 chapter draft), Intent; Also Known As; Solution; Structure; Known Uses; Consequences; See Also
  2. Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, introduction; Table of Contents, 3 Event Handling Patterns
  3. concurrent.futures, Launching parallel tasks, Python documentation, ThreadPoolExecutor Example; as_completed
  4. io_uring(7), Linux manual page, DESCRIPTION, user_data

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/3FNX6W/text.yaml