> For the complete documentation index, see [llms.txt](https://docs.cennso.com/components/tposs/latest/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/latest/configuration/session.md).

# Session management

This document describes how to configure various aspects of TPOSS behaviour during creating and managing [network](https://docs.cennso.com/components/tposs/latest/glossary.md#network-session) and [service](https://docs.cennso.com/components/tposs/latest/glossary.md#service-session) sessions, further mentioned as [PCS](https://docs.cennso.com/components/tposs/latest/glossary.md#telecom-abbreviations) sessions.

## Session handler locking

TPOSS uses a global lock across all TPOSS instances within a cluster to avoid potential race conditions in a case when multiple incoming requests arrive for the same identifier (like `IMSI` or `Session-Id`). 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 that uses the [NATS](https://nats.io/)-based Cennso Data Mesh (CDM) 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 cannot 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/latest/technical-reference/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.

> [!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", "custom", or the NATS service name defined in **nats-services.{NATS_SERVICE_NAME}**.
    algorithm: "global-lock-service-name"
```

All the locking algorithms and providers except **nats-services.{SERVICE_NAME}** do not have additional configuration options. If you are using **nats-services.{SERVICE_NAME}**, make sure to configure the respective [Global lock service](https://docs.cennso.com/components/tposs/latest/configuration/nats-services/global-lock.md) as well.

## 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.{SESSION-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.{SESSION-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.only_older_than**. The **sessions.ggsn.disconnect_without_framed_ip.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 behavior, see the [Troubleshooting guide](https://docs.cennso.com/components/tposs/latest/troubleshooting/idle_timer.md#idle-timer-issues).

## 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/latest/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/latest/troubleshooting/cleanup.md#disable-clean-up-of-outdated-service-sessions).

## Sessions cache

> [!CAUTION]
> The features described below 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.

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
```
