You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Overhaul stats: Add extendable-labeled metrics to the tracker-core package #1437
As I have mentioned here I could not add extendable-labeled metrics for torrents and peers in this issue because I first need to add events to the tracker-core package.
tracker_core_torrents_added_total <- Number of torrents added
tracker_core_torrents_removed_total{peerless="true"} <- Number of peerless torrents removed because they don't have peers
Peers
Prefix: tracker_core_peers_
Type: Counter
Labels:
inactive: true or false
Examples:
tracker_core_peers_added_total <- Number of peers that have been added
tracker_core_peers_removed_total <- Number of peers that have been removed
tracker_core_peers_removed_total{inactive="true"} <- Number of peers that have been removed because of inactivity
tracker_core_peers_completed_total <- Number of peers that have completed
We could include both proposals.
3. Calculate metrics on demand vs keeping metrics updated
Currently, the metrics are calculated on demand. The torrent repository offers several methods for retrieving swarm statistics and aggregate swarm statistics.
On demand
Pros:
It only affects performance when the API receives a request (currently every 15 seconds from the Prometheus service).
Cons:
It does not scale well. With millions of torrents and hundreds of peers per torrent, it would be slow O(n*m)
Updated metrics
Pros:
No time needed to calculate them in the API endpoint.
Cons:
Overhead for each request to update metrics.
4. How to resolve new metrics for inactive torrents/peers
@devnakx proposed including metrics for inactive torrents and peers.
Torrents and peers are not marked as inactive. We only include the latest update time.
Inactive peers are those whose latest update time is older than the config.tracker_policy.max_peer_timeout value.
We have several options for calculating these metrics.
Option 1. Iterate over all torrents and peers (on demand).
Option 2. Add new events for when a torrent or peer is activated or deactivated. They are activated when their "update" time changes, and they go into inactivity when the latest "update" time is longer than config.tracker_policy.max_peer_timeout. We still need a cronjob for "deactivation".
I would use option 1. We can have two types of metrics: those that are maintained when new events are triggered and those that are calculated on demand. These could be of the second type.
are calculated by iterating over the torrent repository:
let mut repository_seeders = 0;
let mut repository_leechers = 0;
for each torrent in torrent_repository {
let mut torrent_peers = 0;
let mut torrent_seeders = 0;
let mut torrent_leechers = 0;
for each peer in torrent.peer_list {
torrent_peers++;
if peer.is_seeder() {
torrent_seeders++;
}
}
torrent_leechers = torrent_peers - torrent_seeders
repository_seeders += torrent_seeders
repository_leechers += torrent_leechers
}
These provide duplicate peers in the global torrent repository metrics because some peers are the same seeding and/or leeching different torrents.
I think we should count unique peers (using the peer ID), and we will likely need a secondary data structure to store the list of peers. This can also be calculated on demand.
6. Should we merge torrent-repository and tracker-core packages?
There are some metrics that we can calculate within the torrent-repository package; however, for other metrics, such as those related to inactivity, we depend on configuration values that are only known by the tracker core.
I think the complexity could be reduced by merging these two packages. However, I won't do it for now, since we want to share the torrent-repository as a crate.
6. Plan
I will:
Add events to the torrent-repository package.
Add maintained metrics updated via events.
Add on-demand metrics (inactivity and accurate seeders and leechers counters).
In the beginning, I wanted to use the labeled metrics (new API metrics endpoint), but the cardinality is too high. That's another example of metrics that maybe we can extract on demand (related to point 3).
Perhaps we should retain the old /stats endpoint for metrics collected from live data structures, and the new /metrics endpoint for metrics that are continuously updated in a separate statistics data structure.
State Management (active/inactive status computation)
View Layer (Metrics Exposure):
Prometheus HTTP endpoint (/metrics)
Text-based format serializer
Exposition protocol handler
Key MVVM Advantages for Metrics:
Separation of Concerns:
Model: Pure data storage/retrieval ("What we track")
ViewModel: Metric business logic ("How we interpret")
View: Presentation/formatting ("How we expose")
Performance Handling:
Precompute metrics incrementally (on events)
Cache expiration strategies for inactive peers
Batch updates for high-frequency events
Label Management:
structPeerLabels{status:Arc<AtomicBool>,seeder:AtomicBool,leecher:AtomicBool,last_updated:AtomicU64}implLabelStrategy{fnupdate(&self,config:&Config){// Atomic updates based on config thresholds}}
metrics.on_peer_update(|peer| {
vm.handle_peer_update(peer)// Incremental update});
metrics.on_scrape(|| {
vm.precompute_complex_metrics()// Expensive ops only during scrape});
This would allow mixing event-driven updates (for basic counters) with on-demand computation (for inactive status checks) while keeping configuration-dependent logic contained in the ViewModel.
Today, in our weekly meeting @da2ce7 and I decided to:
Use these new names for more accurate peer metrics:
✅ Unique peers (real peers):
unique_seeders — number of unique peers currently seeding any torrent.
unique_leechers — number of unique peers currently leeching any torrent.
📦 Torrent-peer relationships (per torrent count):
torrent_seeders — total number of torrents being seeded across all peers (e.g., a peer seeding 3 torrents adds +3).
torrent_leechers — total number of torrents being leeched across all peers.
Implement proposals 2 and 1
Start by adding "event" metrics:
peers added
peers removed
seeder added
seeder removed
And continue adding "aggregate" metrics like:
current number of peers
current number of seeders
current number of leechers
The second group of metrics (proposal 1) could be calculated by the metrics consumer from the first group, but to make consumers' lives easier, we would also include the second type, which we think is even more useful than the first. In fact, we want to include the first to expose info that otherwise would not be accessible to external consumers of the metrics unless they poll very often.
Priorize event-driven metrics over on-demand (real-time) metrics
The tracker has two main responsibilities:
Serve peer list to clients.
Return internal statistics to third-party systems like indexes.
We consider the first to be the central tracker's responsibility and the other a secondary responsibility. Observability is essential, but whenever we have two choices, we always prefer the one that does not affect the performance of the tracker's main purpose.
On-demand metrics affect the performance more than the asynchronous metrics if you have many API metrics consumers.
In the end, all the new labeled metrics have been added to the torrent-repository except one.
We need to add this metric to the tracker-core:
torrent_repository_persistent_torrents_downloads_total: The total number of torrent downloads (since persistence for statistics was enabled).
NOTE: I'm using the persistent prefix after the package name prefix to indicate this metric is persisted.
The torrent-repository only contains in-memory data structures and does not handle persistence at all. The only package in the application that handles persistence is the tracker-core.
In this case, we need to persist the value for this metric because we want to keep the value across multiple restars of the tracker.
My plan for the implementation is:
Add the scaffolding to listed to torrent-repository events. This is also needed here.
Add the scaffolding for metrics.
In the event handler, when we receive a PeerDownloadCompleted and we:
We increase the in-memory value of the counter
We persist the new value in the database
Scaffolding to persist metric values.
When the tracker starts, we need to load the value for the new metric from the database and initialise it.
Start using this value in the old stats endpoint to fix this this issue.
NOTICE: This requires creating a new table to persist metrics. It might not be trivial to persist metrics and measurements (labels) in different tables.
NOTES:
Although we already persist the number of downloads for each torrent, we need the global counter because it's impossible to sum the values when you have millions of torrents. See this issue.
A table with the download counters for all torrents.
A table with values for persisted metrics.
We could remove the "old" table in the future if we don't need to persist more info about a torrent (only the number of downloads). We could add labels to the new metric with the infohash and persist those counters as metrics. But I'm not planning to do that now because we must keep the current table due to backwards compatibility.
QUESTIONS
Should we include the code to persist the metrics in the tracker-core, or should we also add optional persistence to the metrics crate? That would allow us to persist any metric in other packages. I think I'm going to put the logic in the tracker-core, and we can move it to the metrics package if we need it in another package. It would be complex to add persistence independently in two packages.
Should we include the code to persist the metrics in the tracker-core, or should we also add optional persistence to the metrics crate? That would allow us to persist any metric in other packages. I think I'm going to put the logic in the tracker-core, and we can move it to the metrics package if we need it in another package. It would be complex to add persistence independently in two packages.
I decided only to persist metrics in the tracke-core and only the metrics we currently persist:
Activity
josecelano commentedon Apr 21, 2025
I've been thinking about this issue. I have some doubts.
1. Refactor events to use labels (proposal 1)
Following recent changes and conventions, it may make sense to use a single metric with multiple labels.
Torrents
tracker_core_torrents_A torrent is considered inactive if:
Peers
tracker_core_peers_A peer is considered inactive if its last update timestamp was more than
config.tracker_policy.max_peer_timeoutseconds ago.2. Refactor events to use labels (proposal 2)
Torrents
Prefix:
tracker_core_torrents_Type: Counter
Labels:
Examples:
Peers
Prefix:
tracker_core_peers_Type: Counter
Labels:
Examples:
We could include both proposals.
3. Calculate metrics on demand vs keeping metrics updated
Currently, the metrics are calculated on demand. The torrent repository offers several methods for retrieving swarm statistics and aggregate swarm statistics.
On demand
Pros:
Cons:
Updated metrics
Pros:
Cons:
4. How to resolve new metrics for inactive torrents/peers
@devnakx proposed including metrics for inactive torrents and peers.
Torrents and peers are not marked as inactive. We only include the latest update time.
Inactive peers are those whose latest update time is older than the
config.tracker_policy.max_peer_timeoutvalue.We have several options for calculating these metrics.
config.tracker_policy.max_peer_timeout. We still need a cronjob for "deactivation".I would use option 1. We can have two types of metrics: those that are maintained when new events are triggered and those that are calculated on demand. These could be of the second type.
5. Metrics accuracy
The current torrents and peers metrics:
{ "torrents": 706240, "seeders": 187753, "completed": 1200202, "leechers": 306611 }are calculated by iterating over the torrent repository:
These provide duplicate peers in the global torrent repository metrics because some peers are the same seeding and/or leeching different torrents.
I think we should count unique peers (using the peer ID), and we will likely need a secondary data structure to store the list of peers. This can also be calculated on demand.
6. Should we merge
torrent-repositoryandtracker-corepackages?There are some metrics that we can calculate within the
torrent-repositorypackage; however, for other metrics, such as those related to inactivity, we depend on configuration values that are only known by the tracker core.I think the complexity could be reduced by merging these two packages. However, I won't do it for now, since we want to share the
torrent-repositoryas a crate.6. Plan
I will:
torrent-repositorypackage.cc @da2ce7
josecelano commentedon Apr 23, 2025
Relates to point 3: #1456 (comment)
I want to add a counter for all BitTorrent client implementations that are sending the incorrect connection ID.
In the beginning, I wanted to use the labeled metrics (new API
metricsendpoint), but the cardinality is too high. That's another example of metrics that maybe we can extract on demand (related to point 3).Perhaps we should retain the old
/statsendpoint for metrics collected from live data structures, and the new/metricsendpoint for metrics that are continuously updated in a separate statistics data structure.cc @da2ce7
josecelano commentedon Apr 24, 2025
Relates to point 5: #1437 (comment)
Regarding metrics accuracy (point 5 avobe), I think we should rename the metrics to represent better what they are counting:
✅ Unique peers (real peers):
seeder— number of unique peers currently seeding any torrent.leecher— number of unique peers currently leeching any torrent.📦 Torrent-peer relationships (per torrent count):
seeded_torrents— total number of torrents being seeded across all peers (e.g., a peer seeding 3 torrents adds +3).leeching_torrents— total number of torrents being leeched across all peers.The current values for seeder and leecher are the second ones.
cc @da2ce7
da2ce7 commentedon May 5, 2025
Here's how MVVM could be applied to metrics architecture:
Key MVVM Advantages for Metrics:
Your Case Considerations:
torrent-repository(data structure focused)tracker-core(business logic aware)This would allow mixing event-driven updates (for basic counters) with on-demand computation (for inactive status checks) while keeping configuration-dependent logic contained in the ViewModel.
da2ce7 commentedon May 5, 2025
The ViewModel prepares metric states (not raw data formats)
It defines logical representations like:
Key Responsibilities:
Type Conversion
Transforms raw repository data into metric primitives:
Label Orchestration
Handles combinatorial cases like
seeder="true",leecher="true":Format Abstraction
Maintains metric states agnostic to output format:
Why This Matters for Your Design:
Multiple Proposal Support
You could implement switchable strategies:
Performance Isolation
Heavy operations like inactive peer detection can be hidden behind async boundaries:
Consistent Label Handling
Prevents invalid combinations like
seeder="false",leecher="false"at the type level:This architecture lets you:
josecelano commentedon May 5, 2025
Today, in our weekly meeting @da2ce7 and I decided to:
✅ Unique peers (real peers):
unique_seeders— number of unique peers currently seeding any torrent.unique_leechers— number of unique peers currently leeching any torrent.📦 Torrent-peer relationships (per torrent count):
torrent_seeders— total number of torrents being seeded across all peers (e.g., a peer seeding 3 torrents adds +3).torrent_leechers— total number of torrents being leeched across all peers.Start by adding "event" metrics:
And continue adding "aggregate" metrics like:
The second group of metrics (proposal 1) could be calculated by the metrics consumer from the first group, but to make consumers' lives easier, we would also include the second type, which we think is even more useful than the first. In fact, we want to include the first to expose info that otherwise would not be accessible to external consumers of the metrics unless they poll very often.
The tracker has two main responsibilities:
We consider the first to be the central tracker's responsibility and the other a secondary responsibility. Observability is essential, but whenever we have two choices, we always prefer the one that does not affect the performance of the tracker's main purpose.
On-demand metrics affect the performance more than the asynchronous metrics if you have many API metrics consumers.
josecelano commentedon May 16, 2025
In the end, all the new labeled metrics have been added to the
torrent-repositoryexcept one.We need to add this metric to the tracker-core:
torrent_repository_persistent_torrents_downloads_total: The total number of torrent downloads (since persistence for statistics was enabled).NOTE: I'm using the
persistentprefix after the package name prefix to indicate this metric is persisted.The
torrent-repositoryonly contains in-memory data structures and does not handle persistence at all. The only package in the application that handles persistence is thetracker-core.In this case, we need to persist the value for this metric because we want to keep the value across multiple restars of the tracker.
My plan for the implementation is:
torrent-repositoryevents. This is also needed here.PeerDownloadCompletedand we:statsendpoint to fix this this issue.NOTICE: This requires creating a new table to persist metrics. It might not be trivial to persist metrics and measurements (labels) in different tables.
NOTES:
AnnounceHandlerpersist number of downloads intracker-corepackage #1524, but it's a different feature. We will have two different features:QUESTIONS
metricscrate? That would allow us to persist any metric in other packages. I think I'm going to put the logic in the tracker-core, and we can move it to themetricspackage if we need it in another package. It would be complex to add persistence independently in two packages.cc @da2ce7
josecelano commentedon May 27, 2025
I decided only to persist metrics in the
tracke-coreand only the metrics we currently persist:josecelano commentedon May 27, 2025
Completed.