IMD SolutionComputing LibraryShop main store

Troubleshooting

Why InfluxDB queries run slow from a SCADA script

Edge computing and IIoT Published 5 min read

Short answer

The 6-second retrieval is end-to-end client time: a new InfluxDBClient per call, an unfiltered SELECT * over every series, and an iterator consumed outside the measurement. Filter on tagid and a half-open time window, build the client once, and time construction, query and consumption separately before changing the storage design.

On this page
  1. What the six seconds contain
  2. Check what is stored before changing the query
  3. Filter by tag and time in one WHERE clause
  4. Time the three stages separately
  5. Reuse one client for every retrieval
  6. What to check on the server side
  7. The decision for each case
  8. Questions asked

The six seconds are not InfluxDB working through the month of samples. They are the client-side path around the query: a new InfluxDBClient built on every call, a SELECT * with no time bound pulling every series in the measurement, and an iterator handed back before a single point has been consumed. Filter on tagid and a half-open time window in one WHERE clause, construct the client once, and time build, query and consumption as three stages. On the reported test set — InfluxDB OSS 1.8.5 on Windows 10, five-minute samples through May 2021 in one series — a ten-day window returns 2,880 of the 8,928 points, so 67.7% less data moves, decodes and iterates. Do that before changing the storage design.

What the six seconds contain #

The reported retrieval pattern collapses four stages into one measured number:

from influxdb import InfluxDBClient

connector = InfluxDBClient(host=HOST, port=PORT, username=ADMIN, password=PASSWORD)
query = 'select * from "historian"."autogen"."tag_history"'
results = connector.query(query)
return results.get_points()
  • Client construction: TCP setup and authentication run inside the measured window on every call.
  • The HTTP round trip that carries the request.
  • Response decoding and result construction inside query().
  • Iterator creation: get_points() returns a generator, so the point-by-point consumption that fills the display sits outside the measured call but inside the time the operator waits.

At 6.0 s for 8,928 points, the end-to-end budget is 6.0 ÷ 8,928 = 0.672 ms per point from construction to iterator creation. The SQL Server comparison, about 1 s over the same 20 attempts, likely measures different boundaries — a pooled connection and rows materialized inside the call. Align the stages before reading it as a store-versus-store verdict.

Check what is stored before changing the query #

Setting or value Kind Role
historian database target of the fully qualified name
autogen retention policy default policy the name resolves through
tag_history measurement where the samples land
tagid = '1' tag indexed series key mapping to the Ignition tag
value from -5 to 5 field the simulated process value; its field name is not in the reported setup, so read it from the measurement schema before selecting it
5-minute spacing point time 12 samples per hour

InfluxQL treats those two column kinds differently: equality on a tag resolves through the series index, while a predicate on a field scans stored values. Keep the identity you select history by — tagid here — in the tag, and the changing process value in a field.

Verify the endpoints before wiring a display: first timestamp, last timestamp, returned tagid, and the count. Twelve samples per hour over 31 days is 8,928 when June 1 at midnight is excluded, and 8,929 when both endpoints are counted.

Filter by tag and time in one WHERE clause #

The reported statement has no WHERE at all: every series, every field, all time. Two narrower forms were tried separately — a closed range ending in time <= '2021-05-20T00:00:00Z', and a lone tagid equality — and neither moved the number. That is expected: the test data holds a single series, so the tag filter returns the same points, and a time bound alone leaves the per-call client cost untouched.

Combine the restrictions so the query states what the operator actually selected:

SELECT *
FROM "historian"."autogen"."tag_history"
WHERE "tagid" = '1'
  AND time >= '2021-05-10T00:00:00Z'
  AND time <  '2021-05-20T00:00:00Z'

The tag equality picks the series through the index, the time bounds limit which shards the engine reads, and >= paired with < forms a half-open window: May 10–20 and May 20–30 join without duplicating the shared midnight sample. The <= form is valid InfluxQL but answers a different request.

Worked example on the reported data set:

  • Full month: 31 days × 24 hours × 12 samples per hour = 8,928 points (744 hours; 744 × 12 = 8,928).
  • Ten-day half-open window: 10 × 24 × 12 = 2,880 points.
  • Reduction: 8,928 − 2,880 = 6,048 points not transferred; 6,048 ÷ 8,928 = 0.677, so 67.7% less payload to decode and iterate.
  • Boundary check: closing the upper bound adds one sample, giving 2,881.

Once the value field's name is known, select that field instead of *; the saving is small with one field in the measurement and proportional with several. And if a filter that used to return rows comes back empty after the writer changed a field's type, that is troubleshooting empty queries after a field conversion, not slowness.

Time the three stages separately #

  1. Time client construction alone.
  2. Time connector.query(query): transport, decode, result construction.
  3. Time full consumption — list(results.get_points()) — including conversion to whatever the trend binds to.
  4. Repeat every variant over the same 20 attempts before comparing averages.
import time
from influxdb import InfluxDBClient

HOST = "192.168.10.20"       # str: illustrative InfluxDB host
PORT = 8086                  # int: default InfluxDB HTTP port
ADMIN = "history_reader"     # str: illustrative account with read access
PASSWORD = "hist-reader-pw"  # str: illustrative credential

QUERY = "SELECT * FROM \"historian\".\"autogen\".\"tag_history\" WHERE \"tagid\" = '1' AND time >= '2021-05-10T00:00:00Z' AND time < '2021-05-20T00:00:00Z'"

t0 = time.perf_counter()
connector = InfluxDBClient(host=HOST, port=PORT, username=ADMIN, password=PASSWORD)
t1 = time.perf_counter()
results = connector.query(QUERY)
t2 = time.perf_counter()
points = list(results.get_points())
t3 = time.perf_counter()

print("build_s", t1 - t0)    # float seconds, stage 1
print("query_s", t2 - t1)    # float seconds, stage 2
print("consume_s", t3 - t2)  # float seconds, stage 3
assert len(points) == 2880   # ten-day half-open window, one series

The assert proves the filter and the window behave as computed. Whichever stage holds the bulk gets the fix: build cost means reuse the client, query cost means shrink the payload, consumption cost means materialize once.

Reuse one client for every retrieval #

Constructing InfluxDBClient inside the function puts connection setup and authentication into every retrieval. Build it once — module scope in the script, or the platform's long-lived scripting scope — and call .query() per request; the client keeps its HTTP session, so repeat calls skip per-call setup.

The newer influxdb-client-python package can query a 1.8 server through its compatibility path, but it speaks Flux rather than InfluxQL and restructures result handling. Treat it as a rewrite to measure against your staged numbers, not a drop-in speedup.

What to check on the server side #

  • Keep the data directory on local disk. The network-share layout is the same one that leaves an InfluxDB database locked on a network share, and it inflates read latency even when it does not lock.
  • Check concurrent load: writes, compactions and other queries compete for the same disk and CPU.
  • Watch series cardinality: each distinct tagid value is another series, and every tag filter resolves through that index.
  • Match the payload to the display: field selection and window length set the bytes on the wire.

The decision for each case #

  • Unfiltered SELECT * and a client built per call: apply the combined WHERE and reuse the client. A ten-day view then moves 2,880 points instead of 8,928, and per-call connection setup disappears.
  • Filters and reuse in place, retrieval still in seconds: the residual is payload and transport. Shorten the window, select the single value field, or run the query from a host next to the database instead of across the plant network.
  • Query stage fast, screen still waits: the cost is consumption. Materialize the points once into the structure the trend binds to rather than re-walking the iterator each refresh.
  • Custom client path no longer worth maintaining: use Ignition's built-in tag historian with store-and-forward, and start from where the Ignition Edge tag historian writes its data when choosing the storage layout.

Questions asked

Why did the tagid filter alone not speed the query up?

In the reported data every stored point already carries tagid = '1', so the filter changes the plan but returns the same 8,928 points: nothing less is transferred or decoded. A tag filter pays off when several tags share the measurement, because each distinct tagid value is its own indexed series. Pair it with a time bound so the response actually shrinks.

How many points should the filtered ten-day query return?

At five-minute sampling one series yields 12 points per hour, so a half-open ten-day window returns 2,880 points. Closing the upper bound with <= adds the boundary sample and gives 2,881. If you select several tagid values at once, multiply 2,880 by that count, because each tag value is a separate series.

Is the newer influxdb-client-python package a drop-in speedup on 1.8?

No. It reaches a 1.8 server through the compatibility path and speaks Flux instead of InfluxQL, so the query and the result handling must be rewritten and re-measured. Its optional Flux Profiler package can print per-operation profiling of Flux queries, which makes it useful as a diagnostic client even if production keeps the old library.

Why does SQL Server return the same points in about one second?

The two measurements do not share timing boundaries. The SQL path likely reuses a pooled connection and materializes rows inside its measured call, while the InfluxDB path builds a client each time and returns an iterator nobody has consumed yet. Stage both sides identically before treating 1 s versus 6 s as a property of the store.

Should the process value be stored as a tag so filters are indexed?

No. Tags are indexed strings that define series identity; the changing measurement belongs in a field. A continuously varying value in a tag creates a new series per distinct value and multiplies series cardinality, which degrades every query against the measurement. Keep tagid as the tag and the process value as a field.

Keep reading

  • Troubleshooting

    Citect SCADA connector to Historian shows disconnected

    A "Disconnected" destination status means the Citect SCADA Connector has no session to Historian and is buffering samples to local disk. SMC tag-discovery and write entries prove the connector's stages, not that values were archived. Stop the connector, verify the destination instance, services and write authorization, reconnect once, and close only when a query returns a sample and the buffer drains.

    Edge computing and IIoT

  • Troubleshooting

    Fix ECONNREFUSED when Node-RED connects to a remote SQL database

    ECONNREFUSED 127.0.0.1:3306 means the MySQL node dialed loopback on the machine running Node-RED, so the database computer was never contacted. Put the database computer's LAN address in the node's Host field, confirm MariaDB listens on that interface with TCP 3306 open, and create the account with the edge device's address as its host part.

    Edge computing and IIoT

  • Troubleshooting

    Historian tagnames showing a ? prefix mean hidden spaces

    A ? prefix on a tagname in an aahDBDump export marks a hidden space-type character in the stored name, not a corrupt tag or lost history. Find every affected tag with a CHARINDEX query on dbo.Tag in the Runtime database, then rename them with the aahTagRename utility (TN Hist235), which preserves history and needs Historian stopped and disabled under store-and-forward protection.

    Edge computing and IIoT