> For the complete documentation index, see [llms.txt](https://docs.facephi.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.facephi.com/docs.facephi-en/sdks/backend-sdk/selphid/installation/installation_instructions_service.md).

# Service installation and deployment

## 1. Introduction

The service is containerized, and a Docker image is available in a Facephi repository.

```bash
docker login facephicorp.jfrog.io
user: username
pass: token
```

```bash
docker pull facephicorp.jfrog.io/docker-pro-fphi/facephi-selphid-sdk:#VERSION#
```

Where `#VERSION#` is the specific version number you want to download (e.g. `6.22.0`).

{% hint style="warning" %}
**Important** Starting with version 6.15.0, Selphid-sdk Docker is available in three variants.

* `facephi-selphid-sdk:#VERSION#`: Full service, as before.
* `facephi-selphid-sdk:facial-#VERSION#`: Facial extraction, 1:1 authentication, and 1:N authentication service.
* `facephi-selphid-sdk:liveness-#VERSION#`: Passive liveness service. All three variants are deployed in the same way, and their endpoints are consumed in the same way. The difference is that the **facial** and **liveness** variants do not respond to all endpoints, only to those related to their functionality.
  {% endhint %}

## 2. docker-compose

One way to deploy the service is to create a file named `docker-compose.yml` with the following content, changing the variable values as needed.

```yaml
version: '3.7'

services:
  selphid-service:
    ports:
      - "8080:8080"
    volumes:
      -  /home/user/selphid/config:/app/selphid-sdk/config
    image: facephicorp.jfrog.io/docker-pro-fphi/facephi-selphid-sdk:#VERSION#
    container_name: facephi-selphid-sdk
```

First, create a user directory with read and write permissions, for example, `/home/user/selphid/config`, and place these two files in it:

* The license file `license.lic` (required).
* The service configuration file `config.json` (optional).

{% hint style="info" %}
The service will write log files to the same directory.
{% endhint %}

Run the following command from the folder containing the file `docker-compose.yml`, to deploy the service:

```
docker compose up
```

## 3. Additional configuration

Following the steps in **Section 2**, the service is ready to start. If you need to create additional volumes for different types of assets, you can use the following additional configurations.

### 3.1 License

You can mount an additional volume and define the environment variable `LICENSE_PATH`, if you want to install the license outside the usual configuration directory.

```yaml
version: '3.7'

services:
  selphid-service:
    ports:
      - "8080:8080"
    volumes:
      -  /home/user/selphi/config:/app/selphid-sdk/config
      -  /home/user/license:/app/selphid-sdk/license
    image: facephicorp.jfrog.io/docker-pro-fphi/facephi-selphid-sdk:#VERSION#
    environment:
      LICENSE_PATH: /app/selphid-sdk/license
    container_name: facephi-selphid-sdk
```

{% hint style="info" %}
`LICENSE_PATH` is a folder containing the `license.lic` with read and write permissions. In this example, `/home/user/license/license.lic`.
{% endhint %}

### 3.2 Service

If you need to configure the service, you must provide a `config.json`, as described in **section 2**. If you want to place this file in an additional volume:

```yaml
version: '3.7'

services:
  selphid-service:
    ports:
      - "8080:8080"
    volumes:
      -  /home/user/selphi/config:/app/selphid-sdk/config
      -  /home/user/service:/app/selphid-sdk/service
    image: facephicorp.jfrog.io/docker-pro-fphi/facephi-selphid-sdk:#VERSION#
    environment:
      CONFIG_FILE: /app/selphid-sdk/service/config.json
    container_name: facephi-selphid-sdk
```

{% hint style="info" %}
`CONFIG_FILE` is the path to the configuration file in the additional volume.
{% endhint %}

If no `config.json`is specified, the following default values are used:

```json
{
    "port": 8080,                   # Service port number.
    "number_of_threads": 0,         # The number of IO threads, 0 = the number of CPU cores.
    "connection_timeout": 0,        # The lifetime of the connection without read or write.
    "keep_alive_request_number": 0, # Set the maximum number of requests that can be served through one keep-alive connection.
                                    # After the maximum number of requests are made, the connection is closed.
                                    # The default value of 0 means no limit.
    "client_max_body_size": 100,    # The maximum size of the body allowed in the requests in Mb.
                                    # The default value of 100 Mb.
    "logger_path" : "./logs",       # Set the path to store log files.
    "logger_level" : "info",        # Possible values are [trace|debug|info|warning|error|critical|off].
    "logger_rotation" : "daily",    # Possible values are [hourly|daily].
    "logger_max_files" : 0,         # The default value of 0 means no limit.
    "metrics_enabled" : true,       # Collects the traffic, saturation and latency counters published by /metrics.
    "auth_enabled" : false,         # Requires a JWT on the protected endpoints (see section 4).
    "auth_jwt_secret" : "",         # HS256 shared secret used to validate the JWTs.
    "auth_accept_authorization_header" : true,   # Accepts the JWT in "Authorization: Bearer <jwt>".
    "auth_accept_api_key_header" : true,         # Accepts the JWT in the API key header.
    "auth_api_key_header_name" : "x-api-key",    # Name of the API key header.
    "metrics_saturation_queue_p95_ms" : 250,     # Classification thresholds of /metrics (see section 6.5).
    "metrics_saturation_min_inflight_ratio" : 1.0,
    "metrics_error_rate_warning" : 0.05,
    "metrics_idle_rps_threshold" : 0.01,
    "metrics_quality_alert_window_seconds" : 900
}
```

JWT authentication is optional and disabled by default. Its operation is described in **section 4**, and the operational metrics and their thresholds are described in **section 6**.

Starting with version 6.19.0, the following environment variables have been added to set the values in `config.json`:

```
FACEPHI_SELPHID_REST_PORT=8080
FACEPHI_SELPHID_REST_NUMBER_OF_THREADS=2
FACEPHI_SELPHID_REST_CONNECTION_TIMEOUT=100
FACEPHI_SELPHID_REST_KEEP_ALIVE_REQUEST_NUMBER=0
FACEPHI_SELPHID_REST_CLIENT_MAX_BODY_SIZE=100
FACEPHI_SELPHID_REST_LOGGER_PATH=./logs
FACEPHI_SELPHID_REST_LOGGER_FILE_PREFIX=prefix
FACEPHI_SELPHID_REST_LOGGER_LEVEL=info
FACEPHI_SELPHID_REST_LOGGER_ROTATION=daily
FACEPHI_SELPHID_REST_LOGGER_MAX_FILES=0
```

Starting with version 6.22.0, JWT authentication and operational metrics variables are also supported:

```
FACEPHI_SELPHID_REST_METRICS_ENABLED=true
FACEPHI_SELPHID_REST_AUTH_ENABLED=false
FACEPHI_SELPHID_REST_AUTH_JWT_SECRET=shared-secret
FACEPHI_SELPHID_REST_AUTH_ACCEPT_AUTHORIZATION_HEADER=true
FACEPHI_SELPHID_REST_AUTH_ACCEPT_API_KEY_HEADER=true
FACEPHI_SELPHID_REST_AUTH_API_KEY_HEADER_NAME=x-api-key
FACEPHI_SELPHID_REST_METRICS_SATURATION_QUEUE_P95_MS=250
FACEPHI_SELPHID_REST_METRICS_SATURATION_MIN_INFLIGHT_RATIO=1.0
FACEPHI_SELPHID_REST_METRICS_ERROR_RATE_WARNING=0.05
FACEPHI_SELPHID_REST_METRICS_IDLE_RPS_THRESHOLD=0.01
FACEPHI_SELPHID_REST_METRICS_QUALITY_ALERT_WINDOW_SECONDS=900
```

Environment variables take precedence over `config.json`, and both take precedence over the default values.

The configuration cannot be modified at runtime: to change it, update `config.json` or the environment variables and restart the service. Starting with version 6.22.0, `POST /api/v1/selphid/config` always responds with `400 Bad Request` and a `message` indicating the reason (up to version 6.21.0, it responded `200` without applying any changes).

### 3.3 Debug and usage paths

Finally, you can specify a specific volume/path with read and write permissions for SDK debug information and SDK usage data, using the environment variables `DEBUG_PATH` and `USAGE_PATH`:

```yaml
version: '3.7'

services:
  selphid-service:
    ports:
      - "8080:8080"
    volumes:
      -  /home/user/selphi/config:/app/selphid-sdk/config
      -  /home/user/debug:/app/selphid-sdk/debug
      -  /home/user/usage:/app/selphid-sdk/usage
    image: facephicorp.jfrog.io/docker-pro-fphi/facephi-selphid-sdk:#VERSION#
    environment:
      DEBUG_PATH: /app/selphid-sdk/debug
      USAGE_PATH: /app/selphid-sdk/usage
    container_name: facephi-selphid-sdk
```

## 4. JWT authentication

Starting with version 6.22.0, the service supports optional JWT authentication, disabled by default. It is configured at startup in `config.json` or with the environment variables `FACEPHI_SELPHID_REST_AUTH_*`:

| Parameter                          | Environment variable                                    | Default     | Description                                                                                                 |
| ---------------------------------- | ------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------- |
| `auth_enabled`                     | `FACEPHI_SELPHID_REST_AUTH_ENABLED`                     | `false`     | Requires a valid JWT on protected endpoints                                                                 |
| `auth_jwt_secret`                  | `FACEPHI_SELPHID_REST_AUTH_JWT_SECRET`                  | `""`        | HS256 shared secret used to validate JWTs                                                                   |
| `auth_accept_authorization_header` | `FACEPHI_SELPHID_REST_AUTH_ACCEPT_AUTHORIZATION_HEADER` | `true`      | Accepts the token in the header `Authorization: Bearer <jwt>`                                               |
| `auth_accept_api_key_header`       | `FACEPHI_SELPHID_REST_AUTH_ACCEPT_API_KEY_HEADER`       | `true`      | Accepts the token as-is, without the prefix `Bearer`, in the header specified by `auth_api_key_header_name` |
| `auth_api_key_header_name`         | `FACEPHI_SELPHID_REST_AUTH_API_KEY_HEADER_NAME`         | `x-api-key` | API key header name                                                                                         |

With authentication enabled:

* All endpoints require a JWT, except `GET /api/v1/selphid/health`, `GET /api/v1/selphid/version`, `GET /api/v1/selphid/metrics`, `GET /api/v1/selphid/metrics/prometheus` and `OPTIONS` requests (CORS preflight).
* The token must be signed with HS256 using `auth_jwt_secret` and include the `exp`claim. The time-based claims (`exp` and, if present, `nbf` and `iat`) are checked with a 60-second tolerance to account for small clock differences, so a token is still accepted for up to 60 seconds after it expires.
* Always set `auth_jwt_secret` when enabling authentication: if it is empty, all protected endpoints respond `401` with `Authentication secret is not configured`.
* Requests without a token or with an invalid token receive `401 Unauthorized`, with the header `WWW-Authenticate: Bearer` and this body:

```json
{
  "status": 401,
  "error": "Unauthorized",
  "message": "Missing authentication token",
  "timeStamp": "2026-10-21T10:00:00Z"
}
```

`message` indicates the reason for the rejection: `Missing authentication token`, `JWT token is expired`, `JWT token is not yet valid`, `JWT token does not include exp claim`, `JWT token validation failed` or `Authentication secret is not configured`.

Authentication parameters are only read at startup:

* `GET /api/v1/selphid/config` never returns the JWT authentication keys.
* `POST /api/v1/selphid/config` rejects JWT authentication keys with `400` and the message `JWT auth settings are not accessible from the config endpoint`. To change them, update `config.json` or the environment variables and restart the service.

Configuration example in `config.json`:

```json
{
    "auth_enabled" : true,
    "auth_jwt_secret" : "replace-with-secret",
    "auth_accept_authorization_header" : true,
    "auth_accept_api_key_header" : true,
    "auth_api_key_header_name" : "x-api-key"
}
```

Example using environment variables in `docker-compose.yml`:

```yaml
    environment:
      FACEPHI_SELPHID_REST_AUTH_ENABLED: "true"
      FACEPHI_SELPHID_REST_AUTH_JWT_SECRET: replace-with-secret
```

Authenticated request example:

```bash
curl -X POST http://localhost:8080/api/v1/selphid/extract \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{"image": "<base64 image>"}'
```

## 5. Health check

`GET /api/v1/selphid/health` checks that the SDK is loaded and responding. It is public even when JWT authentication is enabled, so it can be used in container probes.

When the SDK is initialized and responding, the service returns `200`:

```json
{
  "message": "Healthy",
  "initialized": true,
  "sdk": {
    "healthy": true,
    "initialized": true,
    "lastInitStatus": "OK",
    "lastHealthKnown": true,
    "lastHealthCheckAt": "2026-10-21T10:00:00Z",
    "lastError": ""
  }
}
```

When the SDK could not be loaded at startup or does not respond to the check, the service returns `503 Service Unavailable`. `message` indicates the reason: `SelphID SDK is not initialized` or `SDK health check failed`.

```json
{
  "status": 503,
  "error": "ServiceUnavailable",
  "message": "SDK health check failed",
  "timeStamp": "2026-10-21T10:00:00Z"
}
```

{% hint style="warning" %}
**Contract change in version 6.22.0** Up to version 6.21.0, `GET /api/v1/selphid/health` responded `200` with `"message": "Unhealthy"` when the SDK was unavailable. Starting with version 6.22.0, it responds `503`: review any probes and monitors that read the `message`.
{% endhint %}

The result of the latest check is stored and published in the `state.sdk` block of `GET /api/v1/selphid/metrics`, which never runs the check itself.

## 6. Operational metrics

Starting with version 6.22.0, the service publishes two operational metrics endpoints. They are available in all image variants and are public even when JWT authentication is enabled:

* `GET /api/v1/selphid/metrics`: inexpensive JSON snapshot suitable for frequent queries. It does not call the SDK or run the health check.
* `GET /api/v1/selphid/metrics/prometheus`: the same snapshot in Prometheus text exposition format (see section 6.4).

Traffic, saturation, latency, and quality figures accumulate in memory from service startup, so they reset when the service is restarted.

| Block                        | Contents                                                                                                                                                                                                                                                                                                                                                 |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `schemaVersion`, `timestamp` | Format version (`1.0`) and snapshot time in UTC                                                                                                                                                                                                                                                                                                          |
| `service`                    | `name` (`facephi-selphid-service`), `version`, `pathBase` (`/api/v1/selphid`), `uptimeSeconds` and `configuredThreads`                                                                                                                                                                                                                                   |
| `state`                      | `initialized`, `sdk` (result of the latest call to `/health`: `alive`, `healthy`, `initialized`, `lastHealthKnown`, `lastHealthCheckAt` and `lastError`) and `classification` (see section 6.1)                                                                                                                                                          |
| `traffic`                    | All requests handled, including management requests: `totals` (`requests`, `success`, `clientErrors`, `serverErrors`, `unauthorized`), windows `1m`, `5m` and `15m` (`requests`, `rps`, `successRate`, `errorRate`, `clientErrors`, `serverErrors`, `unauthorized`) and `byEndpoint`, with an entry for each endpoint that has already received requests |
| `saturation`                 | `inflight`, `maxInflight1m`, `configuredThreads`, `queueP95Ms1m` and `backlogSuspected`                                                                                                                                                                                                                                                                  |
| `latency`                    | Latencies in milliseconds (`avg`, `p50`, `p95`, `p99`, `max`) total (`totalMs`), queue (`queueMs`) and SDK processing (`sdkMs`), per window                                                                                                                                                                                                              |
| `usage`                      | Requests handled by each business endpoint in `operations`, with keys `<MÉTODO> <ruta>` (for example `POST /api/v1/selphid/extract`), and their sum in `total`. It does not include management endpoints (`health`, `version`, `config` and `metrics`). `enabled` is always `true`                                                                       |
| `quality`                    | Aggregated quality of the SDK results (see section 6.2)                                                                                                                                                                                                                                                                                                  |
| `alerts`                     | Active alerts (see section 6.3)                                                                                                                                                                                                                                                                                                                          |

* `state.sdk` reflects the latest call to `GET /api/v1/selphid/health`. Until the first call, `lastHealthKnown`, `alive` and `healthy` are `false`, without the service being classified as `unhealthy`. To keep this block up to date, configure a probe that periodically calls `/health`.
* `errorRate` counts all `4xx` and `5xx`, including `401` and rejections `400` due to validation errors.

Example (abbreviated):

```json
{
  "schemaVersion": "1.0",
  "timestamp": "2026-10-21T10:00:00Z",
  "service": {
    "name": "facephi-selphid-service",
    "version": "6.22.0",
    "pathBase": "/api/v1/selphid",
    "uptimeSeconds": 3600,
    "configuredThreads": 8
  },
  "state": {
    "initialized": true,
    "classification": "ok",
    "sdk": {
      "alive": true,
      "healthy": true,
      "initialized": true,
      "lastHealthKnown": true,
      "lastHealthCheckAt": "2026-10-21T09:59:30Z",
      "lastError": ""
    }
  },
  "traffic": {
    "totals": { "requests": 1520, "success": 1500, "clientErrors": 20, "serverErrors": 0, "unauthorized": 0 },
    "windows": {
      "5m": { "requests": 95, "rps": 0.32, "successRate": 0.98, "errorRate": 0.02, "clientErrors": 2, "serverErrors": 0, "unauthorized": 0 }
    },
    "byEndpoint": [
      { "method": "POST", "path": "/api/v1/selphid/extract", "requests": 820, "success": 818, "clientErrors": 2, "serverErrors": 0, "unauthorized": 0 }
    ]
  },
  "saturation": { "inflight": 1, "maxInflight1m": 3, "configuredThreads": 8, "queueP95Ms1m": 4, "backlogSuspected": false },
  "latency": { "scope": "global", "windows": { "5m": { "totalMs": { "avg": 120, "p50": 110, "p95": 240, "p99": 320, "max": 410 } } } },
  "usage": {
    "enabled": true,
    "operations": { "POST /api/v1/selphid/extract": 820, "POST /api/v1/selphid/passive-liveness/evaluate": 640 },
    "total": 1460
  },
  "quality": { },
  "alerts": []
}
```

### 6.1 State classification

`state.classification` summarizes the snapshot in a single value:

| Value       | When                                                                                                                                                                                                                                                                                                   |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `unhealthy` | The SDK is not initialized or the last call to `/health` failed                                                                                                                                                                                                                                        |
| `unknown`   | There is no traffic, health checks, or quality alerts yet                                                                                                                                                                                                                                              |
| `saturated` | There is traffic and the request queue indicates saturation: `saturation.backlogSuspected` is `true`, or in-flight requests exceed `configuredThreads × metrics_saturation_min_inflight_ratio` with a 95th-percentile queue latency over the last minute of at least `metrics_saturation_queue_p95_ms` |
| `degraded`  | The 5-minute error rate reaches `metrics_error_rate_warning`, there has been a server error (`5xx`) in the last 5 minutes, or the alert `LOW_QUALITY` is active                                                                                                                                        |
| `idle`      | There is traffic and the requests per second over the last 15 minutes are below `metrics_idle_rps_threshold`                                                                                                                                                                                           |
| `ok`        | None of the above                                                                                                                                                                                                                                                                                      |

Cases are evaluated in the order shown in the table, and the first matching case applies. The comparison with in-flight requests is strict because the request that reads `/metrics` counts as an in-progress request.

### 6.2 Result Quality

The `quality` block aggregates, from service startup, the results returned by the SDK. Requests rejected before reaching the SDK, for example due to validation errors, are not counted. It is an empty object until the first sample: each block appears with its first sample, and `summary`, as soon as any of them appears.

```json
{
  "quality": {
    "facialAuthentication": {
      "samples": 300,
      "positive": 280,
      "negative": 20,
      "similarity": { "samples": 300, "avg": 0.87, "min": 0.02, "max": 0.99 }
    },
    "extraction": {
      "okCount": 818,
      "errorCount": 2,
      "faceConfidence": { "samples": 818, "avg": 0.93, "min": 0.41, "max": 1.0 },
      "facialQualityCounts": { "Good": 790, "Regular": 25, "Bad": 3 }
    },
    "liveness": {
      "diagnosticCounts": { "Live": 600, "NoLive": 35, "Spoof": 3, "NoneBecauseFaceNotFound": 2 },
      "noLiveDetails": {
        "fPadStatusCounts": { "Passed": 600, "Failed": 38 },
        "fPadScore": { "samples": 638, "avg": 0.12, "min": 0.0, "max": 0.98 }
      }
    },
    "tracking": {
      "statusCounts": { "0": 940 }
    },
    "summary": {
      "lowQualitySamples": 7,
      "lowQualitySince": "2026-10-21T09:12:44Z"
    }
  }
}
```

| Block                  | Operations                                                                                                                                                                                           | Contents                                                                                                                                                                                                                       |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `facialAuthentication` | `/authenticate-facial/images`, `/authenticate-facial/image/template`, `/authenticate-facial/templates`, `/authenticate-facial/document/face-image` and `/authenticate-facial/document/face-template` | `samples`, `positive` (`authStatus` equal to `Positive`), `negative` (any other `authStatus`) and the `similarity`                                                                                                             |
| `extraction`           | `/extract` and `/extract/template`                                                                                                                                                                   | `okCount`, `errorCount` (invalid extractions), the summary of `faceConfidence` and the count by `facialQuality` (`facialQualityCounts`)                                                                                        |
| `liveness`             | `/passive-liveness/evaluate` and `/passive-liveness/evaluate/token`                                                                                                                                  | The count by `diagnostic` (`diagnosticCounts`) and, in `noLiveDetails`, the counts by `fPadStatus` and `fMadStatus` (`fPadStatusCounts`, `fMadStatusCounts`) and the summaries of `fPadScore`, `fMadScore` and `coercionScore` |
| `tracking`             | Authentication and liveness check operations                                                                                                                                                         | The count by `trackingStatus` (`statusCounts`)                                                                                                                                                                                 |
| `summary`              | All of the above                                                                                                                                                                                     | `lowQualitySamples` (low-quality samples since startup) and `lowQualitySince` (time of the first one; only appears when there is one)                                                                                          |

The summaries have the form `{ "samples", "avg", "min", "max" }` and only appear when at least one value has been observed.

A sample is low quality only when the SDK could not evaluate it:

* Authentication: `authStatus` equal to `None` or `NoneBecause*` (for example, `NoneBecauseInvalidExtractions`).
* Extraction: invalid extraction (`Invalid Extraction`), `facialQuality` equal to `Bad` or `faceConfidence` less than `0.5`.
* Liveness check: `diagnostic` equal to `None` or `NoneBecause*` (except `NoneBecauseTokenSecurity`), or `fPadStatus`/`fMadStatus` equal to `Error`.

Business verdicts are valid SDK results, not low-quality samples: an authentication `Negative` or `Uncertain`, a diagnostic `Spoof`, `NoLive` or `Uncertain`, a PAD/MAD status `Failed` or `NoneBecauseTokenSecurity` (a token reused in another session, i.e. a detected attack). These are counted in `quality`, but they do not trigger the `LOW_QUALITY` alert or degrade the service classification.

### 6.3 Alerts

| `code`            | `severity` | `message`                                              |
| ----------------- | ---------- | ------------------------------------------------------ |
| `SDK_UNAVAILABLE` | `critical` | `SDK health check failed`                              |
| `HIGH_ERROR_RATE` | `warning`  | `5m error rate is above the warning threshold`         |
| `SATURATED`       | `warning`  | `Queue latency and inflight indicate saturation`       |
| `LOW_QUALITY`     | `warning`  | `Recent SelphID quality signals show degraded results` |
| `IDLE`            | `info`     | `Traffic is below the idle threshold`                  |

Each alert includes `code`, `severity`, `message` and `since` (UTC timestamp):

* `SDK_UNAVAILABLE` is triggered when the SDK is not initialized or the last call to `/health` failed. Its `since` is the time of that check.
* `HIGH_ERROR_RATE` is triggered when the 5-minute error rate, which includes `4xx` and `5xx`, reaches `metrics_error_rate_warning`.
* `SATURATED` and `IDLE` accompany the `saturated` and `idle`.
* `LOW_QUALITY` is triggered by a low-quality sample and remains active while the latest sample occurred within the window `metrics_quality_alert_window_seconds` (900 seconds by default); it clears automatically when that time elapses without any new samples. Its `since` is the first sample for the current alert, not the first one since startup (which is published in `quality.summary.lowQualitySince`). With `0`, the alert is never triggered.
* For `HIGH_ERROR_RATE`, `SATURATED` and `IDLE`, `since` is the timestamp of the snapshot.

### 6.4 Prometheus exposition

`GET /api/v1/selphid/metrics/prometheus` returns the same snapshot as Prometheus exposition text (`text/plain; version=0.0.4; charset=utf-8`). The service-specific series are published first, with the prefix `facephi_selphid_`, followed by the HTTP-level series, with the prefix `facephi_`:

| Series                                                                                                                                                                                                                                                                                      | Type    | Contents                                                                                                                                                         |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `facephi_selphid_service_info{name,version,path_base,schema_version}`                                                                                                                                                                                                                       | gauge   | Block `service`, always with a value of `1`                                                                                                                      |
| `facephi_selphid_configured_threads`, `facephi_selphid_uptime_seconds`                                                                                                                                                                                                                      | gauge   | `service.configuredThreads` and `service.uptimeSeconds`                                                                                                          |
| `facephi_selphid_snapshot_timestamp_seconds`                                                                                                                                                                                                                                                | gauge   | Snapshot timestamp (`timestamp`)                                                                                                                                 |
| `facephi_selphid_initialized`                                                                                                                                                                                                                                                               | gauge   | `state.initialized`                                                                                                                                              |
| `facephi_selphid_sdk_alive`, `facephi_selphid_sdk_last_health_known`, `facephi_selphid_sdk_last_health_check_timestamp_seconds`                                                                                                                                                             | gauge   | Block `state.sdk`                                                                                                                                                |
| `facephi_selphid_state_classification{classification}`                                                                                                                                                                                                                                      | gauge   | `state.classification`: is true `1` for the current value and `0` for the rest                                                                                   |
| `facephi_selphid_usage_counters_enabled`                                                                                                                                                                                                                                                    | gauge   | `usage.enabled`                                                                                                                                                  |
| `facephi_selphid_usage_operations_total{operation}`, `facephi_selphid_usage_total`                                                                                                                                                                                                          | counter | Block `usage`; `operation` is true `<METHOD> <path>`                                                                                                             |
| `facephi_selphid_authentication_samples_total`, `facephi_selphid_authentication_results_total{result}`                                                                                                                                                                                      | counter | `quality.facialAuthentication`; `result` is true `positive` or `negative`                                                                                        |
| `facephi_selphid_extraction_results_total{result}`                                                                                                                                                                                                                                          | counter | `quality.extraction`; `result` is true `ok` or `error`                                                                                                           |
| `facephi_selphid_extraction_facial_quality_total{quality}`                                                                                                                                                                                                                                  | counter | `quality.extraction.facialQualityCounts`                                                                                                                         |
| `facephi_selphid_liveness_diagnostics_total{diagnostic}`                                                                                                                                                                                                                                    | counter | `quality.liveness.diagnosticCounts`                                                                                                                              |
| `facephi_selphid_liveness_fpad_status_total{status}`, `facephi_selphid_liveness_fmad_status_total{status}`                                                                                                                                                                                  | counter | `quality.liveness.noLiveDetails.fPadStatusCounts` and `fMadStatusCounts`                                                                                         |
| `facephi_selphid_tracking_status_total{status}`                                                                                                                                                                                                                                             | counter | `quality.tracking.statusCounts`                                                                                                                                  |
| `facephi_selphid_quality_score_samples`, `facephi_selphid_quality_score_avg`, `facephi_selphid_quality_score_min`, `facephi_selphid_quality_score_max` (labels `operation` and `metric`)                                                                                                    | gauge   | Summaries of `quality`: `similarity` in `facialAuthentication`, `faceConfidence` in `extraction`, and `fPadScore`, `fMadScore` and `coercionScore` in `liveness` |
| `facephi_selphid_low_quality_samples`, `facephi_selphid_low_quality_since_timestamp_seconds`                                                                                                                                                                                                | gauge   | Block `quality.summary`                                                                                                                                          |
| `facephi_selphid_alert_active{code,severity}`, `facephi_selphid_alert_since_timestamp_seconds{code,severity}`                                                                                                                                                                               | gauge   | Block `alerts`: value `1` for active alerts and `0` for the rest                                                                                                 |
| `facephi_requests_total`, `facephi_request_success_total`, `facephi_request_client_errors_total`, `facephi_request_server_errors_total`, `facephi_request_unauthorized_total`                                                                                                               | counter | Block totals `traffic`                                                                                                                                           |
| `facephi_endpoint_requests_total{method,path}`, `facephi_endpoint_request_success_total{method,path}`, `facephi_endpoint_request_client_errors_total{method,path}`, `facephi_endpoint_request_server_errors_total{method,path}`, `facephi_endpoint_request_unauthorized_total{method,path}` | counter | Breakdown of `traffic` by endpoint                                                                                                                               |
| `facephi_endpoint_inflight_requests{method,path}`                                                                                                                                                                                                                                           | gauge   | In-flight requests by endpoint                                                                                                                                   |
| `facephi_window_requests{window}`, `facephi_window_rps{window}`, `facephi_window_success_rate{window}`, `facephi_window_error_rate{window}`, `facephi_window_client_errors{window}`, `facephi_window_server_errors{window}`, `facephi_window_unauthorized{window}`                          | gauge   | Windows `1m`, `5m` and `15m` of `traffic`                                                                                                                        |
| `facephi_inflight_requests`, `facephi_configured_threads`, `facephi_backlog_suspected`, `facephi_max_inflight_requests{window}`                                                                                                                                                             | gauge   | saturation block `saturation`                                                                                                                                    |
| `facephi_total_latency_ms{window,stat}`, `facephi_queue_latency_ms{window,stat}`, `facephi_sdk_latency_ms{window,stat}`                                                                                                                                                                     | gauge   | latency block `latency`, with `stat` equal to `avg`, `p50`, `p95`, `p99` or `max`                                                                                |
| `facephi_total_latency_ms_count{window}` / `_sum{window}` / `_bucket{window,le}` and their queue and processing equivalents                                                                                                                                                                 | gauge   | Count, sum, and cumulative histogram for each latency series within the window                                                                                   |

Exposure notes:

* The `facephi_selphid_*`, global totals, and `saturation` series without labels declare their type with a `# TYPE`line. Endpoint, window, and latency series are published without this line; the “Type” column indicates how to interpret them.
* Classification and alert series always publish all possible values, with `0` when the condition is inactive, so they do not appear and disappear between queries. Sample counts for `quality` are also published, with `0`, before the first operation.
* Series with a count per value (`operation`, `quality`, `diagnostic`, `status`) appear when that value is first observed, and summary `facephi_selphid_quality_score_*` series appear when included in the JSON snapshot.
* Window series (`{window="1m|5m|15m"}`) summarize only requests in that sliding window, so they can decrease between queries.
* Timestamps are published as epoch seconds (`*_timestamp_seconds`) and are set to `0` while the snapshot has not recorded that timestamp.
* Descriptive text (`state.sdk.lastError` and `alerts[].message`) is published only in the JSON response.

### 6.5 Metrics configuration

These parameters are configured at startup in `config.json` or with the specified environment variables, which take precedence. They are not returned by `GET /api/v1/selphid/config` and cannot be changed at runtime. The `metrics_*` thresholds only change how the snapshot is classified and which alerts are published; they do not change request processing.

| Parameter                               | Environment variable                                         | Type    | Default | Description                                                                                                                                                                                                                  |
| --------------------------------------- | ------------------------------------------------------------ | ------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `metrics_enabled`                       | `FACEPHI_SELPHID_REST_METRICS_ENABLED`                       | boolean | `true`  | Records requests in the `traffic`, `saturation` and `latency`blocks. With `false`, no requests are recorded: `traffic`, `latency`, `usage` and the counts for in-flight and queued requests for `saturation` are set to zero |
| `metrics_saturation_queue_p95_ms`       | `FACEPHI_SELPHID_REST_METRICS_SATURATION_QUEUE_P95_MS`       | integer | `250`   | 95th percentile of queue latency over the last minute (ms) above which the queue is considered saturated                                                                                                                     |
| `metrics_saturation_min_inflight_ratio` | `FACEPHI_SELPHID_REST_METRICS_SATURATION_MIN_INFLIGHT_RATIO` | number  | `1.0`   | Fraction of `configuredThreads` that in-flight requests must exceed for the service to be considered saturated                                                                                                               |
| `metrics_error_rate_warning`            | `FACEPHI_SELPHID_REST_METRICS_ERROR_RATE_WARNING`            | number  | `0.05`  | 5-minute error rate (responses `4xx` and `5xx`) above which the service is classified as `degraded` and the alert is triggered `HIGH_ERROR_RATE`                                                                             |
| `metrics_idle_rps_threshold`            | `FACEPHI_SELPHID_REST_METRICS_IDLE_RPS_THRESHOLD`            | number  | `0.01`  | Requests per second over the last 15 minutes below which the service is classified as `idle`                                                                                                                                 |
| `metrics_quality_alert_window_seconds`  | `FACEPHI_SELPHID_REST_METRICS_QUALITY_ALERT_WINDOW_SECONDS`  | integer | `900`   | Window, in seconds, during which a low-quality sample keeps the alert active `LOW_QUALITY`. With `0`, the alert is deactivated                                                                                               |

A `metrics_*` threshold that cannot be parsed, is negative, or is non-finite is discarded with a log warning: if it comes from an environment variable, the value from `config.json`is used; if that is also invalid, the default value is used.
