Available languages: [Python](https://databento.com/docs/examples/basics-live/live-latency.python.md) · [C++](https://databento.com/docs/examples/basics-live/live-latency.cpp.md) · [Rust](https://databento.com/docs/examples/basics-live/live-latency.rust.md) · [HTTP](https://databento.com/docs/examples/basics-live/live-latency.http.md) · [Raw](https://databento.com/docs/examples/basics-live/live-latency.raw.md)

Source: https://databento.com/docs/examples/basics-live/live-latency


# Estimate Databento feed latency

## Overview

In this example we will use the [Live client](https://databento.com/docs/api-live/client/live.md) to calculate latency of incoming records.
We will use the `ts_recv` field to make a measurement of the time between Databento's servers receiving a message from the exchange, to that message being received by the client.
To do this we will request order events for a few symbols using [parent symbology](https://databento.com/docs/conventions/symbology.md#parent) and calculate the latency for each message.

You can read more about Databento's timestamps in this [article](https://databento.com/docs/architecture/timestamping-guide.md).

## MBO schema

We will use the [MBO schema](https://databento.com/docs/schemas/mbo.md) for this example.
This schema provides records for every individual order event.

## Example

```cpp
#include <algorithm>                 // sort
#include <chrono>                    // nanoseconds
#include <databento/datetime.hpp>    // UnixNanos
#include <databento/live.hpp>        // LiveBuilder
#include <databento/publishers.hpp>  // Dataset
#include <databento/record.hpp>      // MboMsg
#include <databento/symbology.hpp>   // kAllSymbols
#include <iostream>

namespace db = databento;

int main() {
  auto client = db::LiveBlocking::Builder()
                    .SetDataset(db::Dataset::GlbxMdp3)
                    .SetKeyFromEnv()
                    .BuildBlocking();
  // First we subscribe to all orders
  client.Subscribe({"ES.FUT"}, db::Schema::Mbo, db::SType::Parent);
  client.Start();

  // Then, we iterate over the records
  std::vector<std::chrono::nanoseconds> samples;
  constexpr size_t num_samples = 1000;
  while (samples.size() < num_samples) {
    auto record = client.NextRecord();
    if (const auto* mbo = record.GetIf<db::MboMsg>()) {
      auto delta = db::UnixNanos::clock::now() - mbo->ts_recv;
      samples.emplace_back(delta);
    }
  }

  // Finally, we calculate the latency percentiles
  std::sort(samples.begin(), samples.end());
  for (auto percentile : {0, 50, 90, 99}) {
    auto sample = samples.at(percentile * samples.size() / 100);
    std::chrono::duration<double, std::milli> millis{sample};
    std::cout << percentile << "p " << millis.count() << "ms\n";
  }
  return 0;
}
```
## Result

Latency results will depend upon the quality of your system clock and internet connection.
Your individual results might be very large or even negative given these factors.

```plaintext
0p 4.49448ms
50p 5.66887ms
90p 10.7711ms
99p 47.5738ms
```


# Estimate Databento feed latency

## Overview

In this example we will use the [Live client](https://databento.com/docs/api-live/client/live.md) to calculate latency of incoming records.
We will use the `ts_recv` field to make a measurement of the time between Databento's servers receiving a message from the exchange, to the message being received by the client.
To do this, we will request [MBP-1](https://databento.com/docs/schemas/mbp-1.md) data for a [parent symbol](https://databento.com/docs/conventions/symbology.md#parent) and calculate the latency for each message.

You can read our [timestamping guide](https://databento.com/docs/architecture/timestamping-guide.md) to learn more about our architecture.

Latency results will depend upon the quality of your system clock and internet connection.
Your individual results might be very large or even negative given these factors.
To obtain the most accurate results, we suggest you sync your clocks to our [NTP service](https://databento.com/docs/architecture/ntp-service.md).

## Example

```python
import time
import databento as db
import matplotlib.pyplot as plt
import numpy as np

# Set parameters
dataset = "GLBX.MDP3"
product = "ES"

num_samples = 5000
percentiles = [50, 90, 95, 99]
num_bins = 100

# Create a live client
live_client = db.Live(key="$YOUR_API_KEY")

# Subscribe to MBP-1 data
live_client.subscribe(
    dataset="GLBX.MDP3",
    schema="mbp-1",
    symbols=f"{product}.FUT",
    stype_in="parent",
)

# Iterate over the live client and calculate latency
latency_ms = []
for record in live_client:
    if isinstance(record, db.MBP1Msg):
        delta = time.time_ns() - record.ts_recv
        latency_ms.append(delta / 1e6)
    if len(latency_ms) >= num_samples:
        break

fig, ax = plt.subplots(figsize=(10, 6))

x_min = min(latency_ms) * 0.95
x_max = max(latency_ms) * 1.05

# Create histogram with log bins
log_bins = np.logspace(np.log10(x_min), np.log10(x_max), num_bins)
n, bins, patches = ax.hist(latency_ms, bins=log_bins, rwidth=0.85, color="C3")
y_max = max(n) * 1.25

percentile_handles = []
percentile_labels = []

# Create percentile lines
for p in percentiles:
    p_value = np.percentile(latency_ms, p)
    line = ax.axvline(p_value, color="C0", linestyle="--", linewidth=1)
    ax.text(p_value, y_max * 0.9, f"{p}th", color="C0", rotation=-90)
    percentile_handles.append(line)
    percentile_labels.append(f"p{p} - {round(p_value, 2)} ms")

# Set log scale and labels
tick_locations = np.logspace(np.log10(x_min), np.log10(x_max), 10)
ax.set_xscale("log")
ax.set_xticks(tick_locations)
ax.set_xticklabels([str(round(x)) for x in tick_locations])
ax.tick_params(axis="x", which="minor", bottom=False, labelbottom=False)

# Set limits and labels
ax.set_xlim(x_min * 0.95, x_max * 1.05)
ax.set_ylim(0, y_max)
ax.set_xlabel("Latency (ms)", fontsize=12)
ax.set_ylabel("Frequency", fontsize=12)
ax.set_title("Latency Distribution", fontsize=14)

# Add legend and display
ax.legend(handles=percentile_handles, labels=percentile_labels)
plt.tight_layout()
plt.show()
```
![Latency plot](https://databento.com/docs/live-latency-0.svg)


# Estimate Databento feed latency

## Overview

In this example we will use the [Live client](https://databento.com/docs/api-live/client/live.md) to calculate latency of incoming records.
We will use the `ts_recv` field to make a measurement of the time between Databento's servers receiving a message from the exchange, to that message being received by the client.
To do this we will request order events for a few symbols using [parent symbology](https://databento.com/docs/conventions/symbology.md#parent) and calculate the latency for each message.

You can read more about Databento's timestamps in this [article](https://databento.com/docs/architecture/timestamping-guide.md).

## MBO schema

We will use the [MBO schema](https://databento.com/docs/schemas/mbo.md) for this example.
This schema provides records for every individual order event.

## Example

```rust
use databento::{
    LiveClient,
    dbn::{MboMsg, SType, Schema},
    live::Subscription,
};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut client = LiveClient::builder()
        .key_from_env()?
        .dataset("GLBX.MDP3")
        .build()
        .await?;
    // First we subscribe to all orders
    client
        .subscribe(
            Subscription::builder()
                .schema(Schema::Mbo)
                .symbols("ES.FUT")
                .stype_in(SType::Parent)
                .build(),
        )
        .await?;
    client.start().await?;
    // Then, we iterate over the records
    const NUM_SAMPLES: usize = 1000;
    let mut samples = Vec::new();
    while let Some(record) = client.next_record().await? {
        if let Some(mbo) = record.get::<MboMsg>() {
            let delta = time::OffsetDateTime::now_utc() - mbo.ts_recv().unwrap();
            samples.push(delta);
            if samples.len() >= NUM_SAMPLES {
                break;
            }
        }
    }

    // Finally, we calculate the latency percentiles
    samples.sort();
    for percentile in [0, 50, 90, 99] {
        let sample = &samples[percentile * samples.len() / 100];
        let latency_ms = sample.whole_milliseconds();
        let latency_ns = sample.subsec_nanoseconds() % 1_000_000;
        println!("{percentile:02}p {latency_ms:3}.{latency_ns:06}ms");
    }
    Ok(())
}
```
## Result

Latency results will depend upon the quality of your system clock and internet connection.
Your individual results might be very large or even negative given these factors.

```plaintext
00p   4.658912ms
50p   5.818663ms
90p   8.842160ms
99p  37.491661ms
```
