Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Integrations

Client Library Patterns for InfluxDB

Use InfluxDB client libraries well. Compare Python, JavaScript and Go clients, write and query patterns, error handling and testing, with a runnable mock client.

Most real applications talk to InfluxDB through an official client library rather than raw HTTP. Libraries exist for Python, JavaScript/TypeScript, Go, Java, C#, PHP, Ruby and more. They hide authentication, serialisation to line protocol, batching and retries. Which library you use depends on the server generation: the 2.x libraries are named like influxdb-client-python, while InfluxDB 3 has its own set (for example influxdb3-python) that talks to the v3 API and returns query results as Apache Arrow tables.

This lesson shows the patterns that matter regardless of language. The code against a real server is read-only here, and a runnable mock client lets you practise the batching and retry logic yourself.

The same job in three languages

Each snippet writes one point and runs one query against an InfluxDB 2.x bucket. They are read-only because no server is attached.

Python:

Python
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS

with InfluxDBClient(url="http://localhost:8086", token=TOKEN, org="my-org") as client:
    write_api = client.write_api(write_options=SYNCHRONOUS)
    write_api.write(bucket="raw", record=Point("room").tag("name", "lab").field("temp_c", 21.4))

    tables = client.query_api().query('''
        from(bucket: "raw") |> range(start: -1h)
          |> filter(fn: (r) => r._measurement == "room")''')
    for table in tables:
        for row in table.records:
            print(row.get_time(), row.get_field(), row.get_value())

JavaScript (Node.js):

JavaScript
import { InfluxDB, Point } from "@influxdata/influxdb-client";

const client = new InfluxDB({ url: "http://localhost:8086", token: process.env.INFLUX_TOKEN });
const writeApi = client.getWriteApi("my-org", "raw", "s");
writeApi.writePoint(new Point("room").tag("name", "lab").floatField("temp_c", 21.4));
await writeApi.close();                         // flushes the buffer

const rows = client.getQueryApi("my-org").iterateRows('from(bucket: "raw") |> range(start: -1h)');
for await (const { values, tableMeta } of rows) {
  console.log(tableMeta.toObject(values));
}

Go:

Go
client := influxdb2.NewClient("http://localhost:8086", token)
defer client.Close()

writeAPI := client.WriteAPIBlocking("my-org", "raw")
p := influxdb2.NewPoint("room",
    map[string]string{"name": "lab"},
    map[string]interface{}{"temp_c": 21.4},
    time.Now())
if err := writeAPI.WritePoint(context.Background(), p); err != nil {
    log.Fatal(err)
}

InfluxDB 3 clients work in the same style but take a database instead of an org and bucket, and queries are SQL strings.

Patterns that apply everywhere

  1. Create one client and reuse it. It owns a connection pool and a buffer.
  2. Choose the write mode on purpose. Synchronous (blocking) writes confirm each batch and are good for scripts and tests. Batching (asynchronous) writes are right for long-running services, but must be closed or flushed on shutdown.
  3. Use the point builder, not string concatenation. Builders escape special characters (spaces, commas, equals signs) in names and values for you and enforce types.
  4. Parameterise queries. Do not paste user input into Flux or SQL text. Use query parameters where the library offers them, or validate against an allow-list.
  5. Handle errors by class: retry network and 5xx errors with backoff, surface 4xx errors to the developer (batching and retries).
  6. Set timeouts. A hung query must not hold a request thread forever.
  7. Close the client in shutdown hooks (with blocks, defer, finally).
  8. Keep tokens out of code, read them from the environment, and use least-privilege tokens: a write-only token for collectors, read-only for dashboards.

A mock client you can run

A real client needs a server, so here is a minimal mock of the batching write API with the logic described above: a buffer, a flush at a size limit, retry with backoff on a flaky "server", and a final flush on close. It only models the behaviour; it is not the InfluxDB client.

JS Stand-in: a batching client with retries

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Comment out client.close() and run again: the last line stays in the buffer and never reaches the server. That is the "missing last point" bug, reproduced.

Reading query results

Libraries return results in different shapes:

  • Flux queries return a stream of tables: each table has columns like _time, _value, _field and the group-key tags. Python gives table and record objects; the library can also return a pandas DataFrame.
  • InfluxDB 3 SQL queries return rows (Arrow record batches), which convert easily to pandas, Polars or plain lists.

Whichever you use, stream large results instead of loading everything into memory, and always bound the query with a time range.

Testing code that uses InfluxDB

  • Unit test your own mapping code (domain object to point). Wrap the client in a small interface so that tests can pass a fake, like the mock above.
  • Integration test against a throwaway InfluxDB in a container, with a test bucket you delete afterwards.
  • Do not test against production.

Common mistakes

  • A new client per call.
  • Fire-and-forget batching writes with no close, losing the tail.
  • Assuming write() raised no error means the data arrived; in asynchronous mode errors arrive in a callback.
  • Building line protocol by hand without escaping spaces or commas.
  • A token with admin rights in an application that only writes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why close or flush a batching writer before the program exits?

    Batching writers hold points in memory until a flush. Closing triggers the final flush.
  2. 2. Which errors does a client usually retry?

    Transient errors may succeed later. Client errors will fail again.
  3. 3. Why use the library's point builder instead of string concatenation?

    Builders produce valid line protocol, including escaping.
  4. 4. Which token should a metrics collector use?

    Least privilege limits the damage if the collector is compromised.

Summary

  • Official libraries exist for many languages; pick the one for your server generation.
  • Reuse one client, choose sync or batching writes deliberately, and always close.
  • Use builders and parameters, set timeouts, retry only transient errors.
  • Wrap the client for tests; use least-privilege tokens.
  • Stream large query results and always bound by time.

Next: MQTT and IoT Ingest