<!-- review: finished -->

<a id="stream-upstream"></a>

# Upstream

Provides context for describing groups of servers that can be used in the [proxy_pass](https://en.angie.software//angie/docs/configuration/modules/stream/stream_proxy.md#s-proxy-pass) directive.

<a id="configuration-example-73"></a>

## Configuration Example

```nginx
upstream backend {
    hash $remote_addr consistent;
    zone backend 1m;

    server backend1.example.com:1935  weight=5;
    server unix:/tmp/backend3;
    server backend3.example.com       service=_example._tcp resolve;

    server backup1.example.com:1935   backup;
    server backup2.example.com:1935   backup;
}

resolver 127.0.0.53 status_zone=resolver;

server {
    listen 1936;
    proxy_pass backend;
}
```

<a id="directives-82"></a>

## Directives

<a id="index-0"></a>

<a id="s-u-upstream"></a>

### upstream

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `upstream` name { ... }   |
|------------------------------------------------------------------------------------------|---------------------------|
| Default                                                                                  | —                         |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | stream                    |

Describes a group of servers. Servers can listen on different ports. In addition, servers listening on TCP and UNIX domain sockets can be mixed.

Example:

```nginx
upstream backend {
    server backend1.example.com:1935 weight=5;
    server 127.0.0.1:1935            max_fails=3 fail_timeout=30s;
    server unix:/tmp/backend2;
    server backend3.example.com:1935 resolve;

    server backup1.example.com:1935  backup;
}
```

<a id="s-round-robin"></a>

By default, connections are distributed between the servers using a weighted round-robin balancing method. In the above example, each 7 connections will be distributed as follows: 5 connections go to backend1.example.com:1935 and one connection to each of the second and third servers.

If an error occurs during communication with a server, the connection will be passed to the next server, and so on until all of the functioning servers will be tried. If communication with all servers fails, the connection will be closed.

<a id="index-1"></a>

<a id="s-u-server"></a>

### server

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `server` address [parameters];   |
|------------------------------------------------------------------------------------------|----------------------------------|
| Default                                                                                  | —                                |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream                         |

Defines the address and other parameters of a server. The address can be specified as a domain name or IP address with an obligatory port, or as a UNIX domain socket path specified after the `unix:` prefix. A domain name that resolves to several IP addresses defines multiple servers at once.

The following parameters can be defined:

| `weight=`number    | Sets the weight of the server; by default, 1.                                                                                                                                                                                                             |
|--------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `max_conns=`number | Limits the maximum number of simultaneous active connections to the proxied server. Default value is `0`, meaning there is no limit. If the server group does not reside in the [shared memory](#s-u-zone), the limitation works per each worker process. |

<a id="s-max-fails"></a>

`max_fails=`number — sets the number of unsuccessful attempts
to communicate with the server
that should happen in the duration set by [fail_timeout](#s-fail-timeout)
to consider the server unavailable;
it is then retried after the same duration.

Here, an unsuccessful attempt is an error or timeout while establishing a
connection with the server.

#### NOTE
If a `server` directive in a group resolves to multiple servers,
its `max_fails` setting applies to each server individually.

If an upstream contains only one server
after all its `server` directives are resolved,
the `max_fails` setting has no effect and will be ignored.

| `max_fails=1`   | The default number of attempts.      |
|-----------------|--------------------------------------|
| `max_fails=0`   | Disables the accounting of attempts. |

<a id="s-fail-timeout"></a>

`fail_timeout=`time — sets the period of time during which a specified number of
unsuccessful attempts to communicate with the server ([max_fails](#s-max-fails)) should happen to consider the server unavailable.
The server then remains unavailable for the same amount of time
before it is retried.

By default, this is set to 10 seconds.

#### NOTE
If a `server` directive in a group resolves to multiple servers,
its `fail_timeout` setting applies to each server individually.

If an upstream contains only one server
after all its `server` directives are resolved,
the `fail_timeout` setting has no effect and will be ignored.

| `backup`      | Marks the server as a backup server. It will be passed requests when the primary servers are unavailable.                                                                                      |
|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `down`        | Marks the server as permanently unavailable.                                                                                                                                                   |
| `drain` (PRO) | Marks the server as draining; this means<br/>it receives only requests from the sessions<br/>that were bound earlier with [sticky](#s-u-sticky).<br/>Otherwise it behaves similarly to `down`. |

#### WARNING
The `backup` parameter cannot be used along with the [hash](#s-u-hash) and [random](#s-u-random) load balancing methods.

The `down` and `drain` parameters are mutually exclusive.

<a id="s-reresolve"></a>

| `resolve`      | Enables monitoring changes to the list of IP addresses that<br/>corresponds to a domain name, updating it without a configuration reload.<br/>The group must reside in a<br/>[shared memory zone](#s-u-zone);<br/>also, a [resolver](https://en.angie.software//angie/docs/configuration/modules/stream/index.md#s-resolver) must be defined.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
|----------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `service=`name | Enables resolving DNS SRV records and sets the service name.<br/>For this parameter to work, the resolve parameter must also be specified,<br/>without specifying the server port in the hostname.<br/><br/>If there are no dots in the service name,<br/>the name is formed according to the RFC standard:<br/>the service name is prefixed with `_`,<br/>then `_tcp` is added after a dot.<br/>Thus, the service name `http` will result in `_http._tcp`.<br/><br/>Angie resolves the SRV records<br/>by combining the normalized service name and the hostname<br/>and obtaining the list of servers for the combination via DNS,<br/>along with their priorities and weights.<br/><br/>- Top-priority SRV records<br/>  (ones that share the minimum priority value)<br/>  resolve to primary servers,<br/>  and other records become backup servers.<br/>  If `backup` is set with `server`,<br/>  top-priority SRV records resolve to backup servers,<br/>  and other records are ignored.<br/>- Weight is similar to the `weight` parameter of the `server` directive.<br/>  If weight is set by both the directive and the SRV record,<br/>  the weight set by the directive is used. |

This example will look up the `_http._tcp.backend.example.com` record:

```nginx
server backend.example.com service=http resolve;
```

| `sid=`id   | Sets the server ID in the group. If the parameter is not specified,<br/>the ID is set as a hexadecimal MD5 hash<br/>of the IP address and port or UNIX domain socket path.   |
|------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

<a id="s-slow-start"></a>

| `slow_start=`time   | Sets the [time](https://en.angie.software//angie/docs/configuration/configfile.md#syntax) for a server to recover its weight<br/>when returning to service<br/>with [round-robin](https://en.angie.software//angie/docs/configuration/modules/http/http_upstream.md#round-robin) or [least_conn](#s-u-least-conn)<br/>load balancing methods.<br/><br/>If the parameter is set<br/>and a server is again considered healthy<br/>after a failure according to [max_fails](#s-max-fails) and [upstream_probe (PRO)](https://en.angie.software//angie/docs/configuration/modules/stream/stream_upstream_probe.md#s-u-upstream-probe),<br/>the server gradually recovers its designated weight<br/>over the specified time period.<br/><br/>If the parameter is not set,<br/>in a similar situation<br/>the server immediately starts working with its designated weight.   |
|---------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### NOTE
If only one `server` is specified in the upstream,
`slow_start` has no effect and will be ignored.

<a id="index-2"></a>

<a id="s-u-state"></a>

### state (PRO)

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `state` file;   |
|------------------------------------------------------------------------------------------|-----------------|
| Default                                                                                  | —               |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream        |

Specifies the file where the upstream server list is persistently stored.
When installing from
[our packages](https://en.angie.software//angie/docs/installation/index.md#install-packages),
a dedicated directory
`/var/lib/angie/state/` (`/var/db/angie/state/` on FreeBSD)
is created with appropriate permissions for storing such files,
so you only need to add the filename in the configuration:

```nginx
upstream backend {

    zone backend 1m;
    state /var/lib/angie/state/<FILE NAME>;
}
```

The server list format here is similar to `s_server`.
The file contents change whenever servers are modified in the
[/config/stream/upstreams/](https://en.angie.software//angie/docs/configuration/modules/http/http_api.md#api-config-stream-upstreams-servers) section
via the configuration API.
The file is read at Angie startup or configuration reload.

#### WARNING
To use the `state` directive in an `upstream` block,
there should be no `server` directives in it,
but a shared memory zone ([zone](#s-u-zone)) is required.

<a id="index-3"></a>

<a id="s-u-zone"></a>

### zone

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `zone` name [size];   |
|------------------------------------------------------------------------------------------|-----------------------|
| Default                                                                                  | —                     |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream              |

Defines the name and size of the shared memory zone that stores the group's configuration and runtime state, shared between worker processes. Multiple groups can use the same zone. In this case, it is sufficient to specify the size only once.

#### NOTE
The zone's content is only preserved on reload when the configured
`size` is unchanged. Any size change — increase or decrease —
causes the zone to be re-created empty.

<a id="index-4"></a>

<a id="s-u-backup-switch"></a>

### backup_switch (PRO)

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `backup_switch` `permanent`[=time];   |
|------------------------------------------------------------------------------------------|---------------------------------------|
| Default                                                                                  | —                                     |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream                              |

The directive enables the ability to start server selection not from the primary group,
but from the *active* group, i.e., the one where a server was successfully found previously.
If a server cannot be found in the active group for the next request,
and the search moves to the backup group,
this backup group becomes active,
and subsequent requests are first directed to servers in this group.

If the `permanent` parameter is defined without a [time](https://en.angie.software//angie/docs/configuration/configfile.md#syntax) value,
the group remains active after selection,
and automatic re-checking of groups with lower priority levels does not occur.
If time is specified,
the active status of the group expires after the specified interval,
and the load balancer again checks groups with lower priority levels,
returning to them if the servers are working normally.

Example:

```nginx
upstream media_backend {
    server primary1.example.com:1935;
    server primary2.example.com:1935;

    server reserve1.example.com:1935 backup;
    server reserve2.example.com:1935 backup;

    backup_switch permanent=2m;
}
```

If the load balancer switches from primary servers to the backup group,
all subsequent requests are handled by this backup group for 2 minutes.
After 2 minutes expire, the load balancer re-checks the primary servers
and makes them active again if they are working normally.

<a id="index-5"></a>

<a id="s-u-feedback"></a>

### feedback (PRO)

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `feedback` variable [`inverse`] [`factor=`number] [`account=`condition_variable];   |
|------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|
| Default                                                                                  | —                                                                                   |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream                                                                            |

Enables a feedback-based load balancing mechanism for the `upstream`.
It dynamically adjusts load balancing decisions
by multiplying each proxied server's weight by the average feedback value,
which changes over time based on the variable value
and is subject to an optional condition.

The following parameters can be specified:

| `variable`   | The variable from which the feedback value is taken.<br/>It should represent a performance or health metric;<br/>it is assumed to be provided by the server.<br/><br/>The value is evaluated with each response from the server<br/>and factored into the moving average<br/>according to `inverse` and `factor` settings.                                                                                                                                                                                                                                                                                                                                                                    |
|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `inverse`    | If the parameter is set, the feedback value is interpreted inversely:<br/>lower values indicate better performance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `factor`     | The factor by which the feedback value is weighted<br/>when calculating the average.<br/>Valid values are integers from 0 to 99.<br/>Default is `90`.<br/><br/>The average is calculated using the [exponential smoothing](https://en.wikipedia.org/wiki/Exponential_smoothing) formula.<br/><br/>The larger the factor, the less new values affect the average;<br/>if `90` is specified, 90% of the previous value will be taken<br/>and only 10% of the new value.                                                                                                                                                                                                                         |
| `account`    | Specifies a condition variable<br/>that controls how connections are accounted for in the calculation.<br/>The average value is updated with the feedback value<br/>only if the condition variable<br/>is not equal to `""` or `"0"`.<br/><br/>#### NOTE<br/>By default, traffic from [probes](https://en.angie.software//angie/docs/configuration/modules/stream/stream_upstream_probe.md#s-u-upstream-probe)<br/>is not included in the calculation;<br/>combining the [$upstream_probe](https://en.angie.software//angie/docs/configuration/modules/http/http_upstream_probe.md#v-upstream-probe) variable<br/>with `account` allows including them<br/>or even excluding everything else. |

Example:

```nginx
upstream backend {

    zone backend 1m;

    feedback $feedback_value factor=80 account=$condition_value;

    server backend1.example.com:1935  weight=1;
    server backend2.example.com:1935  weight=2;
}

map $protocol $feedback_value {
    "TCP"                      100;
    "UDP"                      75;
    default                    10;
}

map $upstream_probe $condition_value {
    "high_priority" "1";
    "low_priority"  "0";
    default         "1";
}
```

This configuration categorizes servers by feedback levels
based on protocols used in individual sessions,
and also adds a condition on [$upstream_probe](https://en.angie.software//angie/docs/configuration/modules/http/http_upstream_probe.md#v-upstream-probe)
to account only for `high_priority` probes
or regular client sessions.

<a id="index-6"></a>

<a id="s-u-hash"></a>

### hash

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `hash` key [`consistent`];   |
|------------------------------------------------------------------------------------------|------------------------------|
| Default                                                                                  | —                            |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream                     |

Specifies a load balancing method for the group where client-server mapping is determined using a hashed key value. The key can contain text, variables, and their combinations. Note that any addition or removal of servers from the group may result in remapping of most keys to different servers. The method is compatible with the Perl [Cache::Memcached](https://metacpan.org/pod/Cache::Memcached) library.

Usage example:

```nginx
hash $remote_addr;
```

When using domain names that resolve to multiple IP addresses
(for example, with the `resolve` parameter),
the server does not sort the received addresses, so their order may differ
across different servers, which affects client distribution.
To ensure consistent distribution,
use the `consistent` parameter.

If the `consistent` parameter is specified, the ketama consistent hashing method will be used instead of the above method. The method ensures that when a server is added to or removed from the group, only a minimal number of keys will be remapped to other servers. Using the method for caching servers provides a higher cache hit ratio. The method is compatible with the Perl [Cache::Memcached::Fast](https://metacpan.org/pod/Cache::Memcached::Fast) library with the `ketama_points` parameter set to 160.

<a id="index-7"></a>

<a id="s-u-least-conn"></a>

### least_conn

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `least_conn`;   |
|------------------------------------------------------------------------------------------|-----------------|
| Default                                                                                  | —               |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream        |

Specifies a load balancing method for the group where a connection is passed to the server with the least number of active connections, taking into account server weights. If several servers are suitable, they are selected cyclically (round-robin) with their weights taken into account.

<a id="index-8"></a>

<a id="s-u-least-time"></a>

### least_time (PRO)

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `least_time` `connect` | `first_byte` | `last_byte` [`factor=`number] [`account=`condition_variable];   |
|------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------|
| Default                                                                                  | —                                                                                                       |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream                                                                                                |

Specifies a load balancing method for the group where the probability of passing
a connection to an active server is inversely proportional to its average
response time; the lower it is, the more connections the server will receive.

| `connect`    | The directive takes into account the average time to establish a connection.   |
|--------------|--------------------------------------------------------------------------------|
| `first_byte` | The directive uses the average time to receive the first byte of the response. |
| `last_byte`  | The directive uses the average time to receive the full response.              |

| `factor`   | Performs the same function as [response_time_factor (PRO)](#s-u-response-time-factor),<br/>and overrides it if the parameter is specified.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
|------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `account`  | Specifies a condition variable<br/>that controls which connections are accounted for in the calculation.<br/>The average value is updated<br/>only if the connection's condition variable<br/>is not equal to `""` or `"0"`.<br/><br/>#### NOTE<br/>By default, [probes](https://en.angie.software//angie/docs/configuration/modules/stream/stream_upstream_probe.md#s-u-upstream-probe)<br/>are not included in the calculation;<br/>combining the [$upstream_probe](https://en.angie.software//angie/docs/configuration/modules/http/http_upstream_probe.md#v-upstream-probe) variable<br/>with `account` allows including them<br/>or even excluding everything else. |

Current values are presented as `connect_time`, `first_byte_time`,
and `last_byte_time` in the server's `health` object
among [upstream metrics](https://en.angie.software//angie/docs/configuration/modules/http/http_api.md#api-status-stream-upstreams) in the API.

<a id="index-9"></a>

<a id="s-u-random"></a>

### random

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `random` [`two`];   |
|------------------------------------------------------------------------------------------|---------------------|
| Default                                                                                  | —                   |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream            |

Specifies a load balancing method for the group where a connection is passed to a randomly selected server, taking into account server weights.

If the optional `two` parameter is specified, Angie randomly selects two servers and then chooses a server using the specified method. The default method is [least_conn](#s-u-least-conn), which passes the connection to the server with the least number of active connections.

<a id="index-10"></a>

<a id="s-u-response-time-factor"></a>

### response_time_factor (PRO)

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `response_time_factor` number;   |
|------------------------------------------------------------------------------------------|----------------------------------|
| Default                                                                                  | `response_time_factor 90;`       |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream                         |

Specifies for the [least_time (PRO)](#s-u-least-time) load balancing method the smoothing
factor for the **previous** value when calculating the average response time using the
[exponentially weighted moving average](https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average) formula.

The larger the specified number, the less new values affect the average; if
`90` is specified, 90% of the previous value will be taken and only 10% of
the new value. Valid values are from 0 to 99 inclusive.

Current calculation results are presented as `connect_time` (time
to establish a connection), `first_byte_time` (time to receive the first
byte of the response), and `last_byte_time` (time to receive the full response) in
the server's `health` object among [upstream metrics](https://en.angie.software//angie/docs/configuration/modules/http/http_api.md#api-status-stream-upstreams) in the API.

#### NOTE
Only successful responses are considered in the calculation;
what constitutes an unsuccessful response
is determined by the [proxy_next_upstream](https://en.angie.software//angie/docs/configuration/modules/stream/stream_proxy.md#s-proxy-next-upstream) directives.

<a id="index-11"></a>

<a id="s-u-sticky"></a>

### sticky

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `sticky route` value...;<br/><br/>`sticky learn` `zone=`zone `create=`$create_var1... `lookup=`$lookup_var1... [`connect`] [`norefresh`] [`timeout=`time];<br/><br/>`sticky learn` `lookup=`$lookup_var1... `remote_action=`uri `remote_result=`$remote_var [`remote_uri=`uri];   |
|------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Default                                                                                  | —                                                                                                                                                                                                                                                                                 |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream                                                                                                                                                                                                                                                                          |

Configures sticky sessions between clients and upstream servers,
depending on the mode specified in the first parameter.
To gradually take servers with `sticky` out of rotation,
you can use the `drain` option (PRO) in the [server](#s-u-server) block.

#### WARNING
The `sticky` directive must appear after all load balancing method directives,
otherwise it won't work.

`route` mode

This mode uses predefined route identifiers
that can be embedded in connection properties accessible to Angie.
It is less flexible as it depends on predefined values,
but is better suited if such identifiers are already in use.

Here, when establishing a connection, the upstream server
can assign a route to the client and return its identifier in a way
known to both parties.
The route identifier
should use the value of the [sid](#s-reresolve) parameter
of the [server](#s-u-server) directive.
Note that the parameter is additionally hashed
if the [sticky_secret](#s-u-sticky-secret) directive is specified.

Subsequent connections from clients wishing to use this route
must contain the identifier issued by the server, in such a way
that it ends up in Angie variables.

The directive parameters specify strings that may include variables
for routing. To select the server where the incoming connection is directed,
the first non-empty value is used;
it is then compared with the [sid](#s-reresolve) parameter
of the [server](#s-u-server) directive.
If server selection fails
or the selected server cannot accept the connection,
another server will be selected
according to the configured load balancing method.

Here Angie looks for the route identifier in the `$route` variable,
which receives its value based on [$ssl_preread_server_name](https://en.angie.software//angie/docs/configuration/modules/stream/stream_ssl_preread.md#v-ssl-preread-server-name)
(note that [ssl_preread](https://en.angie.software//angie/docs/configuration/modules/stream/stream_ssl_preread.md#s-ssl-preread) must be enabled):

```nginx
stream {

    map $ssl_preread_server_name $route {

        a.example.com            a;
        b.example.com            b;
        default                  "";
    }

    upstream backend {

        server 127.0.0.1:8081 sid=a;
        server 127.0.0.1:8082 sid=b;

        sticky route $route;
    }

    server {

        listen 127.0.0.1:8080;

        ssl_preread on;

        proxy_pass backend;
    }
}
```

`learn` mode (PRO)

In this mode, a dynamically generated key is used
to bind a client to a specific upstream server;
this mode is more flexible
as it assigns servers on the fly,
stores sessions in a shared memory zone,
and supports various ways of passing session identifiers.

Here, a session is created
based on connection properties coming from the upstream server.
The `create` and `lookup` parameters list variables
that specify how new sessions are created and existing ones are found.
Both parameters can be used multiple times.

The session identifier is the value of the first non-empty variable
specified with `create`;
for example, this could be
the [upstream server name](https://en.angie.software//angie/docs/configuration/modules/http/index.md#v-server-name).

Sessions are stored in a shared memory zone;
its name and size are specified by the `zone` parameter.
If a session has not been accessed within the [time](https://en.angie.software//angie/docs/configuration/configfile.md#syntax)
specified by `timeout`, it is deleted.
The default value is 1 hour.

By default, Angie extends the session lifetime
by updating the last access timestamp each time it is used.
The `norefresh` parameter changes this behavior:
the session expires strictly by timeout, even if it is being used.

Subsequent connections from clients wishing to use a session
must contain its identifier.
The `lookup` parameter searches for the session identifier in the connection
using the specified list of variables,
stopping at the first non-empty one.
If nothing is found, the request is considered new.
The value of the found identifier
is matched against sessions in shared memory.
If server selection fails
or the selected server cannot handle the connection,
another server will be selected
according to the configured load balancing method.

The `connect` parameter allows creating a session
immediately after establishing a connection with the upstream server.
Without it, the session is created only after connection processing is complete.
(In the case of UDP connections, sessions are created immediately after server selection.)

In the example, Angie creates and looks up sessions
using the [$rdp_cookie](https://en.angie.software//angie/docs/configuration/modules/stream/stream_rdp_preread.md#v-rdp-cookie) variable:

```nginx
stream {

    upstream backend {

        server 127.0.0.1:3390;
        server 127.0.0.1:3391;

        sticky learn lookup=$rdp_cookie create=$rdp_cookie zone=sessions:1m;
    }

    server {

        listen 127.0.0.1:3389;

        rdp_preread on;

        proxy_pass backend;
    }
}
```

`learn` mode with `remote_action` (PRO 1.10.0+)

The `remote_action` and `remote_result` parameters
allow dynamically assigning and managing session identifiers
using a remote session store (PRO).

Unlike `learn` mode with `zone`,
this mode does not cache sessions locally
and queries the remote store for each connection.

The `remote_action` parameter must point to a `location`
in the [client](https://en.angie.software//angie/docs/configuration/modules/http/index.md#client) context.
The `remote_uri` parameter specifies the URI of the client HTTP request
to the specified `location`.
By default, it is `/`.
The `remote_uri` value can contain variables.

The general operating principle of this mode is as follows:
if a session identifier is not found locally,
Angie sends a synchronous subrequest to a remote store
specified by the `remote_action` parameter.

When a new connection arrives, Angie performs the following actions:

- First, the session identifier is extracted from the first non-empty variable
  in the `lookup` list.
  If all variables are empty,
  the normal load balancing algorithm is used without sticky sessions.
- Then Angie sends a synchronous HTTP subrequest to the remote store
  specified by the `remote_action` parameter, which should contain
  in a format understood by the store:
  - the *session* identifier from the `lookup` parameter
    (in the configuration, this is the
    [$sticky_sessid](#v-s-sticky-sessid) variable);
  - the identifier of the preselected *server*:
    the value of the `sid=` parameter from the `server` directive,
    if specified,
    or the MD5 hash of the server name
    (in the configuration, this is the
    [$sticky_sid](#v-s-sticky-sid) variable).

  The `$sticky_sessid` and `$sticky_sid` variables are automatically
  exported to the HTTP context with the `stream_` prefix:
  `$stream_sticky_sessid`, `$stream_sticky_sid`.
  This allows using them directly in HTTP directives,
  for example via HTTP headers using [proxy_set_header](https://en.angie.software//angie/docs/configuration/modules/http/http_proxy.md#proxy-set-header).
- The remote store processes the request and returns an HTTP response:

  A response with code 200, 201, or 204 confirms the selected server.
  The remote store can simultaneously
  return an alternative server identifier in an HTTP header or in the
  response body (PRO); it can be extracted via `remote_result`.

  When receiving any other HTTP code from the store
  (including network errors and timeouts)
  or a non-existent server identifier,
  Angie uses the originally selected server.

The server identifier is extracted from the remote store response
via the `remote_result` parameter:
it can specify variables
with the `upstream_http_` prefix,
which are created automatically by Angie to access
HTTP response headers from the remote store,
or [$sent_body](https://en.angie.software//angie/docs/configuration/modules/http/index.md#v-sent-body) to use the response body.
For example, the `X-Sid: server1` header in such a response
becomes accessible in the `$upstream_http_x_sid` variable
with the value `server1`.

Below is a simplified configuration example.
The remote store returns the server identifier in the `X-Sticky-Sid` header
and thus confirms or overrides Angie's selection:

```nginx
http {

    client {

        location @sticky_client1 {

            # use variables from the stream upstream;
            # it adds these variables to the HTTP context with the stream_* prefix
            proxy_set_header X-Sticky-Sessid $stream_sticky_sessid;
            proxy_set_header X-Sticky-Sid $stream_sticky_sid;
            proxy_set_header X-Sticky-Last $msec;
            proxy_pass http://127.0.0.1:8080;

            proxy_cache remote;
            proxy_cache_valid 200 1d;
            proxy_cache_key $scheme$proxy_host$request_uri$stream_sticky_sessid;
        }
    }
}

stream {

    upstream u {

        server 127.0.0.1:8081 sid=backend-01;
        server 127.0.0.1:8082 sid=backend-02;

        sticky learn lookup=$remote_addr            # stream variable
        remote_action=@sticky_client1               # location from client block
        remote_result=$upstream_http_x_sticky_sid   # HTTP variable
        remote_uri=/foo;                            # default is /
    }

    server {

        listen 127.0.0.1:8080;
        proxy_pass u;
    }
}
```

Here, with the following response from the remote store:

```none
HTTP/1.1 200 OK
...
X-Sticky-Sid: backend-01
X-Session-Info: active
```

Two variables become available:

- `$upstream_http_x_sticky_sid`,
  with the value `backend-01`;
- `$upstream_http_x_session_info`,
  with the value `active`.

Since the `$upstream_http_x_sticky_sid` variable
is specified in the `remote_result` parameter,
its value will be used
to select the server with `sid=backend-01`.

The `sticky` directive takes into account the state of servers in [upstream](#s-u-upstream):

- Servers marked as `down` or temporarily unavailable due to failures
  are excluded from selection.
- Servers that have reached the maximum number of connections
  (when using `max_conns`) are temporarily skipped.
- Servers with the `drain` option (PRO)
  can be selected for creating new sessions in `sticky` mode
  when identifiers match.
- If a previously unavailable server recovers,
  `sticky` automatically resumes using it.

The behavior of `sticky` can be further configured
with the [sticky_secret](#s-u-sticky-secret) and [sticky_strict](#s-u-sticky-strict) directives.
If `sticky` fails to select a server or it is unavailable,
the request will be handled according to the selected load balancing method,
unless the `sticky_strict` directive is enabled.
In `sticky_strict on;` mode, the request is rejected with an error.

Shared memory zones
specified in the `zone` parameter of the `sticky` directive
cannot be shared between different `upstream` groups;
each group must use its own zone.

<a id="index-12"></a>

<a id="s-u-sticky-secret"></a>

### sticky_secret

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `sticky_secret` string;   |
|------------------------------------------------------------------------------------------|---------------------------|
| Default                                                                                  | —                         |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream                  |

Adds string as salt to the MD5 hash function
for the [sticky](#s-u-sticky) directive in `route` mode.
String can contain variables, for example `$remote_addr`:

```nginx
upstream backend {
    server 127.0.0.1:8081 sid=a;
    server 127.0.0.1:8082 sid=b;

    sticky route $route;
    sticky_secret my_secret.$remote_addr;
}
```

The salt is added after the hashed value;
to independently verify the hashing mechanism:

```console
$ echo -n "<VALUE><SALT>" | md5sum
```

<a id="index-13"></a>

<a id="s-u-sticky-strict"></a>

### sticky_strict

| [Syntax](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)   | `sticky_strict` `on` | `off`;   |
|------------------------------------------------------------------------------------------|---------------------------------|
| Default                                                                                  | `sticky_strict off;`            |
| [Context](https://en.angie.software//angie/docs/configuration/configfile.md#configfile)  | upstream                        |

When enabled, Angie will return a connection error to the client
if the desired server is unavailable,
instead of falling back to another available server,
which is the default behavior when no matching server is found.

<a id="built-in-variables-25"></a>

## Built-in Variables

The `stream_upstream` module supports the following built-in variables:

<a id="v-s-sticky-sessid"></a>

### `$sticky_sessid`

Used with `remote_action` in [sticky](#s-u-sticky);
stores the initial session identifier taken from `lookup`.

<a id="v-s-sticky-sid"></a>

### `$sticky_sid`

Used with `remote_action` in [sticky](#s-u-sticky);
stores the server identifier previously associated with the session.

`sticky_sid` contains the value of the `sid=` parameter
from the `server` directive in the [upstream](#s-u-upstream) block, if specified,
or the MD5 hash of the server name.

<a id="v-s-upstream-addr"></a>

### `$upstream_addr`

stores the IP address and port, or the path to the UNIX domain socket of the upstream server. If several servers were contacted during proxying, their addresses are separated by commas, e.g.:

> 192.168.1.1:1935, 192.168.1.2:1935, unix:/tmp/sock

If a server cannot be selected, the variable keeps the name of the [server group](#s-u-upstream).

<a id="v-s-upstream-bytes-received"></a>

### `$upstream_bytes_received`

number of bytes received from an upstream server. Values from several connections are separated by commas and colons like addresses in the [$upstream_addr](#v-s-upstream-addr) variable.

<a id="v-s-upstream-bytes-sent"></a>

### `$upstream_bytes_sent`

number of bytes sent to an upstream server. Values from several connections are separated by commas and colons like addresses in the [$upstream_addr](#v-s-upstream-addr) variable.

<a id="v-s-upstream-connect-time"></a>

### `$upstream_connect_time`

time to connect to the upstream server; the time is kept in seconds with millisecond resolution. Times of several connections are separated by commas and colons like addresses in the [$upstream_addr](#v-s-upstream-addr) variable.

<a id="v-s-upstream-first-byte-time"></a>

### `$upstream_first_byte_time`

time to receive the first byte of data; the time is kept in seconds with millisecond resolution. Times of several connections are separated by commas like addresses in the [$upstream_addr](#v-s-upstream-addr) variable.

<a id="v-s-upstream-session-time"></a>

### `$upstream_session_time`

session duration in seconds with millisecond resolution. Times of several connections are separated by commas like addresses in the [$upstream_addr](#v-s-upstream-addr) variable.

<a id="v-s-upstream-sticky-status"></a>

### `$upstream_sticky_status`

Status of sticky connections.

| `""`   | Connection routed to a server group where sticky is not enabled.                                    |
|--------|-----------------------------------------------------------------------------------------------------|
| `NEW`  | Connection does not contain sticky information.                                                     |
| `HIT`  | Connection with sticky information routed to the desired server.                                    |
| `MISS` | Connection with sticky information routed to a server<br/>selected by the load balancing algorithm. |

Values from multiple connections are separated by commas and colons,
similar to addresses in the [$upstream_addr](#v-s-upstream-addr) variable.
