﻿---
title: The request pipeline
description: How a request travels through the transport: which nodes it asks, when it pings and sniffs, and how it ends. Every box below is a type, an enum value...
url: https://docs-v3-preview.elastic.dev/elastic/elastic-transport-net/pull/313/request-pipeline
products:
  - Elastic Transport .NET
  - Elasticsearch .NET Client
---

# The request pipeline
How a request travels through the transport: which nodes it asks, when it pings and sniffs, and how it ends. Every box below is a type, an enum
value or a method in the code. The behaviour is pinned by the specs in `tests/Elastic.Transport.Tests/ClientConcepts/ConnectionPooling` and by
the model-based properties in `tests/Elastic.Transport.Properties.Tests`.

## One request

`DistributedTransport.RequestCoreAsync` binds the configuration, makes sure the pool has been sniffed once if it should
be, then offers nodes one at a time until one succeeds or the budget is spent. What happens on one node is
`TryNodeAsync`, and its result is a `NodeOutcome`.
```mermaid
flowchart TD
    start([Request]) --> bind["Bind configuration<br/>request-level values win over transport-level ones"]
    bind --> first{"Pool needs its<br/>first sniff?"}
    first -- yes --> sniffStart["Sniff all nodes (SniffsOnStartup)"]
    first -- no --> single
    sniffStart --> single{"Single node,<br/>no ping, no reseed?"}
    single -- yes --> one["CallSingleNodeAsync<br/>retry once if a pooled connection was already closed"]
    single -- no --> next{"NextNode:<br/>budget left?"}
    next -- "no: attempts >= MaxRetries + 1<br/>or elapsed >= 98% of MaxRetryTimeout" --> finish
    next -- yes --> node["Next node from the pool view<br/>(alive, or dead and due for a retry)"]
    node --> try["TryNodeAsync"]
    try --> outcome{"NodeOutcome"}
    outcome -- Succeeded --> finish
    outcome -- Stop --> finish
    outcome -- TryNextNode --> next
    one --> finish
    finish["Finalize: NoNodesAttempted / MaxTimeoutReached /<br/>MaxRetriesReached / bad response, as a TransportException<br/>when ThrowExceptions is set"] --> done([Response])
```

The budget is read from the request's own `RequestAttempt` at every step. It is never shared with another request.

## One node

```mermaid
flowchart TD
    a(["TryNodeAsync(node)"]) --> stale{"Cluster info stale?<br/>(SniffInformationLifeSpan)"}
    stale -- yes --> sniffStale["Sniff (SniffOnStaleCluster)"] --> ping
    stale -- no --> ping{"Pinging enabled and<br/>node IsResurrected?"}
    ping -- yes --> doPing["Ping (separate, short timeout)"]
    doPing -- "401" --> stop
    doPing -- fails --> failed
    doPing -- ok --> callNode
    ping -- no --> callNode["Call the product endpoint"]
    callNode -- "401" --> stop
    callNode --> ok{"Success or a known error?"}
    ok -- yes --> alive["MarkAlive"] --> succeeded
    ok -- no --> cancelled{"Cancelled by the caller?"}
    cancelled -- yes --> stop
    cancelled -- no --> failed
    failed["MarkDead; sniff if SniffsOnConnectionFault<br/>(a reseed makes NextNode start from a fresh view)"] --> tryNext
    succeeded([NodeOutcome.Succeeded])
    tryNext([NodeOutcome.TryNextNode])
    stop([NodeOutcome.Stop])
```

In code the turn is a walk over `NodeStep` (`SniffIfStale`, `PingIfDue`, `Call`, `TakeOutOfRotation`, `Settle`, `Done`);
the failure edges above leave through exceptions that `RequestCoreAsync` classifies. The single-node path is a separate,
shorter loop on purpose: it never pings, sniffs, marks a node dead or alive, and has the one stale-connection retry.
`Stop` is for failures another node cannot fix: bad credentials (on the ping or on the call), an unrecoverable
pipeline failure, and cancellation. None of them marks the node dead: a node that answered 401 is up, and a caller that went away says nothing about the node it was waiting for.
Only one sniff per pool is in flight at a time; a request that finds one running carries on with the nodes it has.
A sniff of a stale cluster is housekeeping. When it fails, the audit trail records `SniffFailure` and the request goes on
to the node it was about to use.

## One node's health

A node's health is the `NodeHealth` union (`Components/NodePool/NodeHealth.cs`). The four states are the four meaningful
combinations of alive, resurrected and failed attempts.
```mermaid
stateDiagram-v2
    [*] --> Untested
    Untested --> Alive: MarkAlive
    Untested --> Dead: MarkDead
    Alive --> Dead: MarkDead
    Dead --> Dead: a request that failed on it (no change)
    Dead --> Resurrected: pool offers it again (deadline passed, or every node is dead)
    Resurrected --> Alive: MarkAlive
    Resurrected --> Dead: MarkDead (failed attempts + 1)
    Alive --> Untested: pool offers it again, so it is pinged first
    Untested: Untested (alive, pinged before first use)
    Alive: Alive (no failures)
    Dead: Dead (until, failed attempts)
    Resurrected: Resurrected (until, failed attempts)
```


| State         | `IsAlive` | `IsResurrected` (ping first) | `FailedAttempts`                      |
|---------------|-----------|------------------------------|---------------------------------------|
| `Untested`    | yes       | yes                          | 0                                     |
| `Alive`       | yes       | no                           | 0                                     |
| `Dead`        | no        | no                           | 1 or more                             |
| `Resurrected` | no        | yes                          | 1 or more, kept so back-off continues |

Transitions are a compare-and-swap of the whole state. A request that fails on a node that is already `Dead` changes nothing: requests that were under
way when the node failed all fail, and they are one outage, not one failed attempt each (the back-off doubles every two attempts and stops at 30 minutes,
so counting each of them would keep a node that was down for seconds out for half an hour). A node that fails after the pool offered it again
(`Resurrected`) goes one attempt further.

## Sniffing

A sniff asks nodes for the cluster topology and reseeds the pool. It tries every node in turn and fails only when all of
them have failed, except that bad credentials end it at once. A successful sniff during a request asks that request
(and only that request) to restart its walk from the new view.

## The whole flow

A request ends in one of six ways: **Success**, **Bad Auth**, **Bad Response**, **Max Retry**, **Retry Timeout** or **Bad Sniff**. The red boxes below are those exits. Ping, Sniff Cluster and Bad Response are the steps that are used on the way, and have flows of their own.
`DiagramSpec` (in `tests/Elastic.Transport.Properties.Tests`) is these flows written as a small program, and `DiagramProperties` generates requests (pool kinds, node answers, pings, sniffs, retry and time budgets) and checks that the transport makes the same calls and ends the same way, for the sync and the async path.

### A request

```mermaid
flowchart TD
    clientCall([Client call]) --> first{"First use of the pool,<br/>and SniffsOnStartup?"}
    first -- yes --> sniff0["Sniff Cluster"]
    sniff0 -- failed --> badSniff
    sniff0 -- ok --> select
    first -- no --> select
    select{"Select node:<br/>budget left?"}
    select -- "no" --> ended
    select -- yes --> stale{"Cluster information stale?<br/>(SniffInformationLifeSpan)"}
    stale -- yes --> sniff1["Sniff Cluster<br/>(housekeeping: a failure is only noted)"] --> needsPing
    stale -- no --> needsPing{"Needs pinging?<br/>(pings enabled, node IsResurrected)"}
    needsPing -- yes --> ping["Ping"]
    ping -- ok --> es
    ping -- "401" --> badAuth
    ping -- failed --> badResponse
    needsPing -- no --> es["Call the node"]
    es --> valid{"Valid response?<br/>(success, or a known error)"}
    valid -- yes --> stable["Mark node alive"] --> success
    valid -- "401" --> badAuth
    valid -- no --> badResponse["Bad Response"]
    badResponse --> retriable{"Retriable?<br/>(502, 503, 504, no answer,<br/>unexpected content type)"}
    retriable -- no --> exitBadResponse
    retriable -- yes --> bad["Mark node dead<br/>(out of rotation)"]
    bad --> fault{"SniffsOnConnectionFault?"}
    fault -- yes --> sniff2["Sniff Cluster, from another node"] --> select
    fault -- no --> select
    ended{"Why?"} -- "elapsed >= 98% of MaxRetryTimeout" --> retryTimeout
    ended -- "attempts reached MaxRetries, MaxRetries > 0" --> maxRetry
    ended -- "no node to ask, or MaxRetries is 0" --> exitBadResponse

    success([Success]):::exit
    badAuth([Bad Auth]):::exit
    exitBadResponse([Bad Response]):::exit
    maxRetry([Max Retry]):::exit
    retryTimeout([Retry Timeout]):::exit
    badSniff([Bad Sniff]):::exit
    classDef exit fill:#fdd,stroke:#c33,color:#600
```

*Select node* is `NextNode`: the pool view hands out alive nodes, and dead ones that are due for another try. The budget is `MaxRetries + 1` attempts, where `MaxRetries` is the configured value, or every node of the pool when none is configured, and never less than the pool allowed when the request started. The elapsed time is read against `MaxRetryTimeout` with a 2% margin.
*Retriable* means an answer another node might not give. A `400` or a `500` is not: the response is returned as the answer of the node that gave it. With `ThrowExceptions` on, it is the exception of the same name.

### Ping

```mermaid
flowchart TD
    a(["Needs pinging"]) --> head["HEAD / on the node<br/>(its own, shorter timeout: PingTimeout)"]
    head --> r{"Answer"}
    r -- "2xx" --> ok(["Call the node"])
    r -- "401" --> auth([Bad Auth]):::exit
    r -- "anything else, or none" --> failed["Ping failed:<br/>node out of rotation (marked dead)"]
    failed --> sniff{"SniffsOnConnectionFault?"}
    sniff -- yes --> s["Sniff Cluster, asking a node other than the one that failed"] --> next(["Select the next node"])
    sniff -- no --> next
    classDef exit fill:#fdd,stroke:#c33,color:#600
```


### Sniff Cluster

```mermaid
flowchart TD
    a(["Sniff Cluster"]) --> accepts{"Does the pool accept updates?<br/>(SupportsReseeding)"}
    accepts -- no --> done([Done])
    accepts -- yes --> one{"A sniff already<br/>running on this pool?"}
    one -- yes --> done
    one -- no --> each["For each node in rotation<br/>(every node when all are dead)"]
    each --> ask["GET _nodes/http,settings"]
    ask --> valid{"Valid response?"}
    valid -- "401" --> badSniff
    valid -- no --> more{"Another node?"}
    more -- yes --> each
    more -- no --> badSniff
    valid -- yes --> nodes{"Lists nodes?"}
    nodes -- yes --> reseed["Reseed the pool<br/>(the request walks the new view)"] --> done
    nodes -- no --> keep["Keep the pool as it is"] --> done
    badSniff([Bad Sniff]):::exit
    classDef exit fill:#fdd,stroke:#c33,color:#600
```

A sniff that fails the request on startup ends it as **Bad Sniff** (`CouldNotStartSniffOnStartup`). A sniff in the middle of a request, after a failed node or of a stale cluster, is housekeeping: the audit trail has `SniffFailure`, and the request goes on with the nodes it has.

### Bad Response

```mermaid
flowchart TD
    a(["Bad Response"]) --> mark["Mark the node dead<br/>(until = now + back-off, failed attempts + 1; nothing changes if it is dead already)"]
    mark --> sniff{"SniffsOnConnectionFault?"}
    sniff -- yes --> s["Sniff Cluster"] --> handled
    sniff -- no --> handled([Handled: select the next node])
```

The back-off grows with the failed attempts, from `DeadTimeout` up to `MaxDeadTimeout`, and a node that comes back is pinged first (`Resurrected`, see [one node's health](#one-nodes-health)).

### Things to know

- **The retry budget.** With no `MaxRetries` configured, a request may try every node of the pool, however many it has. A configured `MaxRetries` is the budget.
- **Stale cluster information** is checked before every node, the first one included.
- **A sniff in the middle of a request is housekeeping.** When it fails, the audit trail has `SniffFailure` and the request goes on with the nodes it has. Only a sniff on startup that fails ends the request, as Bad Sniff.
- **A sniff that lists no nodes** is an answer: the pool keeps the nodes it has.
- **A sniff asks the nodes in rotation.** A dead node is not asked, unless all of them are. Bad credentials in a sniff end it as Bad Sniff, with the bad credentials as the cause.
- **A node that answers 401 is up.** It stays in rotation, and the request ends as Bad Auth (`BadCredentialsNodeHealthTests`).
- **A failed ping takes the node out of rotation**, and the sniff that may follow does not ask that node again.
- **The exit says what ended the request.** A `400`, a `500` or bad credentials end it as the answer of the node that gave it, however many nodes were tried and however long it took. Max Retry and Retry Timeout are reported only when the retries or the time did run out.
- **Max Retry** is also the exit of a request that runs out of nodes after `MaxRetries` attempts, one fewer than its budget of `MaxRetries + 1`. A pool of dead nodes, where one is tried again as a probe, is the case.


## The audit trail

Every step above is an event of the audit trail of the response (`ApiCallDetails.AuditTrail`): `SniffOnStartup`, `PingSuccess` / `PingFailure`, `HealthyResponse`, `BadResponse`, `BadRequest`, `MaxRetriesReached`, `MaxTimeoutReached`, `SniffSuccess` / `SniffFailure` and the rest of `AuditEvent`. A node that answered, with any status, is a `BadResponse` when it was refused, a `BadRequest` when nothing came back. The trail is on the response of a request whichever step the request ended on, a ping or a sniff as well as a call.