High-Throughput SNMP Counter Ingestion into TimescaleDB¶
Note
Published: November 29, 2026
Authors: Written by Gemini 4 Neon, Co-Authored & Reviewed by Carlos Santos (@carlkidcrypto)
Estimated Reading Time: 7 minutes
Tags: ezsnmp • ezsnmp_data_logger • TimescaleDB • PostgreSQL • SNMP • Telemetry
Polling 64-bit interface counters across core routers and leaf-spine switches generates massive volumes of monotonic telemetry. While storing raw SNMP walks in SQLite works well for single-site edge appliances, enterprise networks tracking thousands of interfaces quickly outgrow single-file databases.
To compute accurate bits-per-second (bps) bandwidth rollups across months of history, your ingestion pipeline needs three capabilities: process-isolated SNMP collection, time-partitioned TimescaleDB hypertables, and counter wrap/reboot-safe delta math.
In this tutorial, we will design a TimescaleDB hypertable schema for
ezsnmp_data_logger,
build a high-throughput collector using ezsnmp and pg8000, compute bps rates
that survive router reboots, and automate continuous bandwidth aggregates.
Why TimescaleDB for 64-Bit SNMP Counters?¶
High-speed links (10G, 40G, 100G, and 400G) overflow 32-bit ifInOctets
counters in seconds. Modern pipelines always poll 64-bit IF-MIB counters—
ifHCInOctets (.1.3.6.1.2.1.31.1.1.1.6) and ifHCOutOctets
(.1.3.6.1.2.1.31.1.1.1.10)—which store cumulative bytes since the last
counter reset or device reboot.
Storing these counters in a TimescaleDB hypertable gives your monitoring stack:
Automatic Temporal Chunking: Partitioning by
time_stampkeeps active write indexes pinned in RAM while older chunks compress cleanly.Native Columnar Compression: Compressing aged SNMP counter chunks frequently cuts disk usage by 85–90%.
Continuous Aggregates: Pre-computed 5-minute and hourly bandwidth views keep Grafana dashboards responsive over 90-day windows.
Designing the Hypertable Schema¶
Initialize your PostgreSQL database with TimescaleDB and create the
snmp_interface_counters hypertable:
CREATE EXTENSION IF NOT EXISTS timescaledb;
CREATE TABLE IF NOT EXISTS snmp_interface_counters (
time_stamp TIMESTAMPTZ NOT NULL,
host TEXT NOT NULL,
if_index INTEGER NOT NULL,
if_descr TEXT,
sys_uptime_cs BIGINT,
in_octets BIGINT,
out_octets BIGINT,
PRIMARY KEY (time_stamp, host, if_index)
);
SELECT create_hypertable(
'snmp_interface_counters',
'time_stamp',
chunk_time_interval => INTERVAL '7 days',
if_not_exists => TRUE
);
CREATE INDEX IF NOT EXISTS idx_snmp_host_if_time
ON snmp_interface_counters (host, if_index, time_stamp DESC);
Notice sys_uptime_cs (sysUpTime.0 in hundredths of a second). Storing
uptime alongside interface counters lets SQL queries distinguish a normal
counter increase from a device reboot that reset counters to zero.
Process-Isolated Ingestion with ezsnmp & pg8000¶
Because Net-SNMP maintains process-global C state protected by internal
mutexes, scaling across dozens of switches is safest with
concurrent.futures.ProcessPoolExecutor (with each worker creating its own
ezsnmp.Session). Remember to configure set_max_repeaters_to_num=25 on
the constructor, unpack Result.index and Result.type, and verify row
completeness across independent column walks (which run sequentially and can
see transient index mismatches during rapid interface churn):
import os
from concurrent.futures import ProcessPoolExecutor, as_completed
from datetime import datetime, timezone
from typing import Any, List
import pg8000.native
from ezsnmp import Session
from ezsnmp.exceptions import ConnectionError, GenericError, TimeoutError
OID_SYS_UPTIME = "1.3.6.1.2.1.1.3.0"
OID_IF_DESCR = "1.3.6.1.2.1.2.2.1.2"
OID_HC_IN_OCTETS = "1.3.6.1.2.1.31.1.1.1.6"
OID_HC_OUT_OCTETS = "1.3.6.1.2.1.31.1.1.1.10"
def safe_int(val: Any, default: int = 0) -> int:
digits = "".join(c for c in str(val) if c.isdigit() or c == "-")
return int(digits) if digits and digits != "-" else default
def poll_switch(host: str, community: str = "public") -> List[dict]:
ts = datetime.now(timezone.utc)
rows: List[dict] = []
with Session(
hostname=host,
community=community,
version=2,
timeout=2,
retries=1,
set_max_repeaters_to_num=25,
print_enums_numerically=True,
) as session:
try:
uptime_var = session.get(OID_SYS_UPTIME)[0]
uptime_cs = (
safe_int(uptime_var.value)
if uptime_var.type not in ("NOSUCHOBJECT", "NOSUCHINSTANCE")
else 0
)
descrs = {
v.index: v.value
for v in session.bulk_walk(OID_IF_DESCR)
if v.type not in ("NOSUCHOBJECT", "NOSUCHINSTANCE")
}
in_octs = {
v.index: safe_int(v.value)
for v in session.bulk_walk(OID_HC_IN_OCTETS)
if v.type not in ("NOSUCHOBJECT", "NOSUCHINSTANCE")
}
out_octs = {
v.index: safe_int(v.value)
for v in session.bulk_walk(OID_HC_OUT_OCTETS)
if v.type not in ("NOSUCHOBJECT", "NOSUCHINSTANCE")
}
for idx, descr in descrs.items():
if idx not in in_octs or idx not in out_octs:
continue
rows.append(
{
"ts": ts,
"host": host,
"if_index": safe_int(idx),
"if_descr": descr,
"uptime": uptime_cs,
"in_oct": in_octs[idx],
"out_oct": out_octs[idx],
}
)
except (TimeoutError, ConnectionError, GenericError) as err:
print(f"[{host}] SNMP poll error: {err}")
return rows
def ingest_fleet(hosts: List[str]) -> None:
batch: List[dict] = []
with ProcessPoolExecutor(max_workers=4) as pool:
futures = {pool.submit(poll_switch, h): h for h in hosts}
for fut in as_completed(futures):
batch.extend(fut.result())
if not batch:
return
conn = pg8000.native.Connection(
user=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
host=os.environ.get("DB_HOST", "localhost"),
port=int(os.environ.get("DB_PORT", "5432")),
database=os.environ.get("DB_NAME", "net_telemetry"),
)
try:
insert_sql = '''
INSERT INTO snmp_interface_counters (
time_stamp, host, if_index, if_descr,
sys_uptime_cs, in_octets, out_octets
) VALUES (
:ts, :host, :if_index, :if_descr,
:uptime, :in_oct, :out_oct
)
ON CONFLICT (time_stamp, host, if_index) DO NOTHING
'''
for row in batch:
conn.run(insert_sql, **row)
print(f"[+] Inserted {len(batch)} interface counter samples.")
finally:
conn.close()
Handling Counter Wraps & Reboots in SQL¶
Raw Counter64 values increase monotonically until either a 64-bit wrap
(rare on 64-bit counters) or a switch reboot (common). Using PostgreSQL’s
LAG() window function, skip negative deltas caused by reboots or resets
before converting bytes-per-second into Megabits-per-second (Mbps):
WITH counter_deltas AS (
SELECT
time_stamp,
host,
if_descr,
in_octets - LAG(in_octets) OVER w AS delta_in,
EXTRACT(
EPOCH FROM (time_stamp - LAG(time_stamp) OVER w)
) AS delta_sec,
sys_uptime_cs - LAG(sys_uptime_cs) OVER w AS delta_uptime
FROM snmp_interface_counters
WHERE time_stamp >= NOW() - INTERVAL '24 hours'
WINDOW w AS (
PARTITION BY host, if_index
ORDER BY time_stamp
)
)
SELECT
time_bucket('5 minutes', time_stamp) AS bucket,
host,
if_descr,
ROUND(
AVG((delta_in * 8.0 / NULLIF(delta_sec, 0)) / 1000000.0)::numeric,
2
) AS avg_rx_mbps
FROM counter_deltas
WHERE delta_in >= 0
AND delta_uptime >= 0
AND delta_sec > 0
GROUP BY bucket, host, if_descr
ORDER BY bucket DESC;
Adding Compression & Retention Policies¶
Keep long-term storage lean with TimescaleDB native compression after 14 days and automatic chunk expiration after 180 days:
ALTER TABLE snmp_interface_counters SET (
timescaledb.compress,
timescaledb.compress_segmentby = 'host, if_index',
timescaledb.compress_orderby = 'time_stamp DESC'
);
SELECT add_compression_policy(
'snmp_interface_counters', INTERVAL '14 days'
);
SELECT add_retention_policy(
'snmp_interface_counters', INTERVAL '180 days'
);
Summary & What’s Next¶
Combining process-isolated ezsnmp workers with TimescaleDB hypertables turns ezsnmp_data_logger into a resilient, high-throughput network telemetry warehouse with accurate, reboot-safe bandwidth analytics.
In our next blog post, we will rotate to shared-workflows, exploring automated PyPI and multi-architecture Docker release pipelines using GitHub OIDC Trusted Publishing without static API tokens.
Warning
AI-generated content may contain misinformation or mistakes. A human does review this, but we are only human.