> For the complete documentation index, see [llms.txt](https://docs.cennso.com/components/tposs/6.16/llms.txt) (all documentation: [llms.txt](https://docs.cennso.com/llms.txt)). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cennso.com/components/tposs/6.16/configuration/session.md).

# Session management

This document describes how to configure TPOSS behaviour when creating and handling network and service sessions, further mentioned as [PCS](https://docs.cennso.com/components/tposs/6.16/glossary.md) sessions.

## Session behaviour

TPOSS provides a couple of configurable parameters that may control different aspects of PCS sessions behaviour.

### Session handler locking

TPOSS uses a global lock across all TPOSS instances within a cluster to avoid potential race conditions in a rare case when multiple incoming requests arrive for the same identifier. Although it is not recommended, you can disable the lock using this option:

```yaml
sessions:
  global_lock_enabled: true
```

>**CAUTION:** The **sessions.global_lock_enabled** configuration option is experimental and should be used with caution. Although the disabled lock may bring significant improvements in resource consumption, it also might be a reason for unexpected behaviour if TPOSS receives two RADIUS or Diameter requests with the same identifier (IMSI or Session-Id) at the same time.

You can use several algorithms or providers to manage the lock when executing handlers of the incoming RADIUS or Diameter requests. Each algorithm offers different performance and reliability characteristics. You can set the algorithm in **sessions.global_lock.algorithm**. Here are the available options:

* The locking mechanism based on the [NATS](https://nats.io/) server. For this setup, the **sessions.global_lock.algorithm** option should match one of the values listed in **nats-services.{SERVICE_NAME}**. Each TPOSS instance is connected to the NATS server and sends messages to the specially configured stream. These streams may accept and store only a single message - this is how the lock is acquired. As soon as the lock must be released, the owner of the lock releases it by purging this message out of the stream. If the message is not purged for a configurable amount of time, it is released by the NATS server based on TTL (time to live). One of the main differences between this algorithm and others is that if TPOSS can not obtain the lock, the incoming RADIUS or Diameter request is rejected instead of waiting for the ability to obtain the lock. To use this locking algorithm, you must deploy a NATS server before TPOSS or use a NATS server provided in the TPOSS Helm chart. For more information, see the [NATS chart configuration](https://docs.cennso.com/components/tposs/6.16/installation/nats.md) document.
* `global` - The lock manager based on the [Erlang/OTP standard library](https://www.erlang.org/doc/man/global#trans-4). The given locking algorithm is reliable but may lead to high resource consumption with increase of the number of instances within the TPOSS clusters.
* `custom` - The most efficient algorithm in the context of resource consumption but may cause locking data loss in situations like netsplits.
* `locks`  - Algorithm implemented by the [locks](https://github.com/uwiger/locks) library which is focused on efficiency in highly distributed setups. It leads to the highest resource consumption for small numbers of TPOSS instances but can be considered as a replacement for `global` in big TPOSS clusters.

>**CAUTION:** The lock based on NATS is recommended for production. All other options can cause issues, especially during TPOSS cluster upgrades. The TPOSS Helm chart uses this lock provider by default and includes all optimal settings.

See the configuration example:

```yaml
sessions:
  global_lock:
    # Enables the global lock for sessions across TPOSS nodes within the TPOSS cluster.
    enabled: true
    # Defines the algorithm or a lock provider to use for locking sessions across a cluster.
    # The possible values are: "global", "locks", "custom", or the NATS service name defined in **nats-services.{NATS_SERVICE_NAME}**.
    algorithm: "global-lock-provider"
```

All the locking algorithms and providers except **nats-services.{SERVICE_NAME}** do not have additional configuration options. The default and recommended lock provider is NATS. If using **nats-services.{SERVICE_NAME}**, make sure to configure the NATS service as well.

For example:

```yaml
sessions:
  global_lock:
    # Enables the global lock for sessions across TPOSS nodes within the TPOSS cluster.
    enabled: true
    # Defines the algorithm or a lock provider to use for locking sessions across a cluster.
    # The possible values are: "global", "locks", "custom", or the NATS service name defined in **nats-services.{NATS_SERVICE_NAME}**.
    algorithm: "global-lock-provider"

nats-services:
  global-lock-provider:
    # Enables support for global lock based on NATS.
    enabled: false
    # Endpoint of the NATS server.
    server: "localhost:4222"
    # NATS service stream name to create locks managed by the lock manager.
    # It is also used as a prefix for the topic names TPOSS uses to send lock messages.
    stream: "TPOSS_LOCK_MGR"
    # Time in milliseconds to re-connect to NATS in case connection is lost.
    backoff_period: 1000
    # Number of connections per stream. In general, TPOSS creates seven streams, so the total
    # number of connections TPOSS tries to establish towards NATS is this number multiplied by seven.
    connections_per_stream: 5
    # Time in milliseconds that specifies how long a lock message is preserved in NATS.
    ttl: 5000
    # The time values that show how many NATS requests were handled for that time or less.
    # The values are translated into Prometheus histogram buckets and are provided in milliseconds.
    request_histogram_buckets: "10, 100, 1000, 5000, 10000"
    # Determines how messages are stored for retention. The possible values are `memory` and `file`.
    storage_type: "memory"
    # Timeout in milliseconds that specifies the maximum wait time for a response from NATS.
    recv_timeout: 3000
    # Timeout in milliseconds that specifies the maximum wait time for the underlying TCP stack to accept a send operation.
    send_timeout: 3000
```

To enable the session locking based on NATS, you must also set **nats-services.{SERVICE_NAME}.enabled** to `true` and specify **nats-services.{SERVICE_NAME}.server** with the endpoint of the NATS server. If **nats-services.{SERVICE_NAME}.enabled** is set to `true` and the **sessions.global_lock.algorithm** is equal to the `{SERVICE_NAME}`, the TPOSS Helm chart starts the [init container](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/) that checks the available NATS server specified in **nats-services.{SERVICE_NAME}.server**. TPOSS container starts only after the init container is connected to one of the NATS instances.

The **nats-services.{SERVICE_NAME}.stream** parameter specifies the name of the [stream](https://docs.nats.io/nats-concepts/jetstream). TPOSS instances use the stream to acquire the lock based on the NATS messages sent for the specific topic. TPOSS creates multiple streams at start-up if they do not exist at the NATS server. The value of **cdr.stream** is used as a prefix to the topics accepted by the stream. You can configure each stream to be used by multiple connections using the **nats-services.{SERVICE_NAME}.connections_per_stream** configuration option. The total number of connections is the number of streams multiplied by the **nats-services.{SERVICE_NAME}.connections_per_stream** value. By default, TPOSS creates seven streams.

If the connection towards NATS is lost, TPOSS tries to establish a new connection. You can configure the timeout between re-tries using the **nats-services.{SERVICE_NAME}.backoff_period** configuration option. You can also use the **nats-services.{SERVICE_NAME}.ttl** configuration option that specifies TTL (time to live) for each message to avoid overflow and situations when messages are not properly deleted.

TPOSS provides a metric to observe RTT (round-trip time) for requests towards NATS. You can configure the histogram buckets using the **nats-services.{SERVICE_NAME}.request_histogram_buckets** configuration option. For more information, see the [Metrics](https://docs.cennso.com/components/tposs/6.16/metrics.md#nats-metrics) document.

The **storage_type** configuration option controls the NATS clients used by TPOSS. If the NATS server is configured with the file storage backend, TPOSS also must have this configuration option set to `file`. Otherwise, `memory` is also suitable.

The **recv_timeout** configuration option specifies how long TPOSS waits for a response from the NATS server. The **send_timeout** configuration option specifies how long TPOSS waits for the underlying TCP stack to accept a send operation. If any timeout is reached, TPOSS closes the NATS connection and tries to create a new one. Any incoming RADIUS or Diameter requests for this session are rejected until a new NATS connection is ready.

TPOSS rejects the incoming RADIUS or Diameter request, closes the connection, and tries to establish a new one.

### Sessions cache settings

All PCS sessions (network and service sessions) are stored in a database. The type of database depends on the value of the **sessions.backend** configuration option. The possible values for this option are:

- `mnesia`
- `mysql`

It is recommended to use a MySQL database for easier upgrade of the TPOSS cluster and stricter data consistency.

There is an **experimental** feature that allows you to store PCS sessions in the in-memory caches during session creation. You can configure this behaviour with the following configuration options:

```yaml
sessions:
  # Enables in-memory cache for PCS sessions
  cache: false
  # Specifies a cache backend for PCS sessions.
  # The possible values are `ets` and `redis`.
  cache_backend: ets
  redis:
    # Hostname of a Redis instance
    host: "localhost"
    # Port used by Redis to accept connections
    port: 6379
    # Username used to connect to Redis
    username: nil
    # Password used to connect to Redis
    password: nil
    # Number of client connections used to connect to Redis
    connections: 50
```

If the **sessions.cache** is enabled, TPOSS stores sessions in the in-memory cache until they are fully established. Only when a session is fully established, it is inserted in to the database. The type of the in-memory cache depends on the value of the **sessions.cache_backend** configuration option. The supported values are:

- `ets`
- `redis`

If the cache backend is set to `redis`, all the other Redis-related configuration options must be configured with the respective values.

Besides caching of the PCS sessions, TPOSS provides support for caching of charging data, such as charging accounts and balances. To enable this feature, use the following configuration option:

```yaml
ccs:
  cache:
    # Enables caching of charging data during the session creation
    enabled: false
```

>**CAUTION:** Both of these features are experimental and must be used with caution. If the **sessions.cache_backend** is set to `ets`, it can be used only with the Diameter Proxy v1.1.0 and the sticky sessions feature enabled.

## Idle session management

Each network and service session is usually stored in the database during the whole session lifetime. However, if TPOSS does not receive any updates (RADIUS or Diameter interim requests) for a given session from PGW or TDF, it may terminate the session as an idle session.

You can configure how long TPOSS stores a network or a service session without receiving any update requests with the **sessions.{SESSSION-TYPE}.keepalive_timeout** parameter. See the configuration example:

```yaml
sessions
  ggsn:
    # Network sessions keepalive period in seconds.
    # Specifies how long a network session is stored in a database if interim requests do not arrive.
    # For environments where TPOSS can't notify PGW about session termination, it should be set to zero.
    keepalive_timeout: 5400
    disconnect_without_framed_ip:
      # If `true`, a RADIUS Disconnect request is sent to PGW if there is no `Framed-IP-Address` in the network sessions.
      # If `false`, the network sessions are deleted without any notification.
      enabled: true
      # Deletes network sessions without a framed IP address only if the session is older
      # than the given number of seconds
      only_older_than: 0
  scg:
    # Service sessions keepalive period in seconds.
    # Specifies how long a service session is stored in a database if interim requests do not arrive.
    keepalive_timeout: 5400
  # Enables or disables the idle timer for network and service sessions.
  idle_timer_enabled: true
  # Interval in milliseconds to check for idle sessions. If set to `0`, the idle timer functionality is disabled. 
  # Setting this option to a too low value may cause high load on the database.
  idle_timer_check_period: 5000
  # Number of idle timer records to fetch from a database at once to check them for expiration.
  idle_timers_check_limit: 1
```

TPOSS starts the idle timer process which executes the following actions:

1. If there are no idle timer records in the database, TPOSS checks the idle time of sessions every **idle_timer_check_period** milliseconds.

   >**CAUTION:** Setting the **idle_timer_check_period** configuration option too low makes TPOSS check idle timers too often, which may lead to a high load on the database. If set to `0`, idle session checks are disabled. It is also recommended to choose a value divisible by `1000` without remainder for easier debugging.

2. When the sessions appear in the database, TPOSS looks for the session that has the earliest expiration time. Then, TPOSS runs the next check after the same number of milliseconds as the earliest expiration time.
3. By default, TPOSS checks sessions one by one. First, it checks sessions with the earliest expiration time. You can control this behaviour with the **idle_timers_check_limit** configuration option that specifies the number of idle sessions TPOSS checks at once. Depending on the type of session, TPOSS performs different actions:
  - If there is an idle service session with the expired timeout, TPOSS terminates it without any notification and deletes it from the database.
  - If there is an idle network session with the expired timeout, TPOSS starts terminating this network session by sending the RADIUS Disconnect request to PGW. However, RADIUS Disconnect requests can be disabled in the TPOSS configuration, either with the **ggsn_creation_on_accounting** set to `false` or **sessions.idle_timer_enabled** set to `false`. In such a case, TPOSS terminates such network session without notification and deletes it from the database.
4. If TPOSS sent the RADIUS Disconnect request to PGW, the further behaviour depends on the response:
  - Disconnect-ACK - TPOSS expects a RADIUS Accounting-Stop request for the network session. The idle timer of the session is prolonged for ten more seconds.
  - Disconnect-NAK - TPOSS immediately terminates the network session and deletes it from the database.
  - If there is no answer, the next try for a session termination is postponed for ten seconds.
5. After TPOSS terminates the session, the idle process keeps checking for the next idle sessions.
6. If there are no more idle timers, the next check is executed in **idle_timer_check_period** milliseconds. If there are multiple idle timers but none of them is expired, the next check is run after the same number of milliseconds as the earliest expiration time.

The idle timer functionality is disabled when:

- The **sessions.idle_timer_enabled** parameter is set to `false`
- The **sessions.{SESSSION-TYPE}.keepalive_timeout** parameter is set to `0`
- The **sessions.idle_timer_check_period** parameter is set to `0`

>**NOTE:** Both **sessions.idle_timer_check_period** and **sessions.idle_timers_check_limit** configuration options are applicable only if **sessions.backend** is set to `mysql`.

The behavior changes if the **sessions.ggsn.disconnect_without_framed_ip.enabled** parameter is set to `false` and the network session does not have a framed IP address. In this case, TPOSS doesn't send a RADIUS Disconnect request to PGW, and the network session and idle timer are deleted at TPOSS without any notifications. The session is deleted only if it exists longer than specified in **sessions.ggsn.disconnect_without_framed_ip.enabled.only_older_than**. The **sessions.ggsn.disconnect_without_framed_ip.enabled.only_older_than** is applicable only if the **sessions.ggsn.disconnect_without_framed_ip.enabled** is set to `true`.

The following diagram describes the idle timer process in a case when TPOSS found an idle network session:

```mermaid
sequenceDiagram

participant PGW
participant RPR
participant TPOSS
participant MySQL

loop Every *sessions.idle_timer_check_period* milliseconds
  TPOSS ->> MySQL: Check for idle sessions
  MySQL ->> TPOSS: Idle session
  note over TPOSS: Found an idle network session
end

alt RADIUS Disconnect requests on idle timer are disabled
  TPOSS ->> MySQL: Delete the idle network session
  MySQL ->> TPOSS: The idle network session is deleted
else
  TPOSS ->> RPR: RADIUS: Disconnect-Request
  RPR   ->> PGW: RADIUS: Disconnect-Request

  alt PGW answers with Disconnect-ACK
    PGW ->> RPR: RADIUS: Disconnect-ACK
    RPR ->> TPOSS: RADIUS: Disconnect-ACK
    PGW ->> RPR: RADIUS: Accounting-Stop
    RPR ->> TPOSS: RADIUS: Accounting-Stop
    TPOSS ->> MySQL: Delete the idle network session
    MySQL ->> TPOSS: The idle network session is deleted
  else PGW answers with Disconnect-NAK
    PGW   ->> RPR: RADIUS: Disconnect-NAK
    RPR   ->> TPOSS: RADIUS: Disconnect-NAK
    TPOSS ->> MySQL: Delete the idle network session
    MySQL ->> TPOSS: The idle network session is deleted
  else No answer or other errors
  note over TPOSS: Prolong the idle timer of a session for 10 more seconds
  end
end
```

In case of any issues with the idle timer process behaviour, see the [Troubleshooting guide](https://docs.cennso.com/components/tposs/6.16/troubleshooting/idle_timer.md#troubleshooting-idle-timer).

## Automatic service session cleanup

>**CAUTION:** Removing a huge amount of data from the TPOSS database at once may cause performance issues in the database. Read the meaning of the configuration options and use them carefully. If the service session cleanup causes issues, read the [troubleshooting guide](https://docs.cennso.com/components/tposs/6.16/troubleshooting/cleanup.md#disable-clean-up-of-outdated-service-sessions).

New TPOSS deployment may have outdated service sessions in the MySQL database restored from backup. TPOSS provides a service that cleans up old service sessions. You can enable and configure this service using the following configuration options:

```yaml
sessions:
  scg:
    cleanup_outdated_service:
      enabled: false
      older_than: "7-days"
      limit: 0
      query_timeout: 60
      check_period: 86400
```

If the **sessions.scg.cleanup_outdated_service.enabled** option is set to `true`, TPOSS runs a process that periodically checks for outdated service sessions and cleans them up. A service session is considered outdated if it was updated earlier than the value specified by the **sessions.scg.cleanup_outdated_service.older_than** configuration option. The time unit can be one of the following:

- second(s)
- minute(s)
- hour(s)
- day(s)
- week(s)
- month(s)
- year(s)

Deleting a huge number of sessions may cause a significant load and impact the database. To control the number of deleted sessions, you can use the **sessions.scg.cleanup_outdated_service.limit** configuration option that specifies the maximum number of sessions to delete at once. If the value of this configuration option is set to `0`, no limit is applied. The **sessions.scg.cleanup_outdated_service.query_timeout** configuration option specifies the maximum timeout in seconds to execute a query. The last configuration option - **sessions.scg.cleanup_outdated_service.check_period** - specifies the timeout in seconds after which the service repeats the check for outdated service sessions. The maximum value of this parameter is `4294967` seconds or `49` days. 

If the given values have a negative impact on the database, you can disable the service at runtime and re-configure it after the TPOSS restart. For more information, see the [troubleshooting guide](https://docs.cennso.com/components/tposs/6.16/troubleshooting/cleanup.md#disable-clean-up-of-outdated-service-sessions).
