Claude Code for InfluxDB: Time Series Data and IoT Metrics — Claude Skills 360 Blog
Blog / AI / Claude Code for InfluxDB: Time Series Data and IoT Metrics
AI

Claude Code for InfluxDB: Time Series Data and IoT Metrics

Published: August 8, 2027
Read time: 5 min read
By: Claude Skills 360

InfluxDB is purpose-built for time series data — high-ingest metrics, IoT sensor streams, and APM telemetry. InfluxDB v3 (Cloud Serverless and Dedicated) uses Apache Arrow Flight SQL for queries and HTTP for writes. @influxdata/influxdb3-client: new InfluxDBClient({ host: INFLUXDB_HOST, token: TOKEN, database: BUCKET }). Write: client.write("cpu,host=server01,region=us-east usage_user=45.2,usage_system=3.1") — line protocol: measurement,tag1=val1,tag2=val2 field1=val1,field2=val2 nanosecond_timestamp. client.writePoints([new Point("temperature").tag("sensor", "s1").floatField("value", 23.5)]) with fluent API. Query with SQL: for await (const row of client.query("SELECT * FROM cpu WHERE time > now() - INTERVAL '1 hour'", { database: BUCKET })). Downsampling: INSERT INTO cpu_1h SELECT time_bucket(INTERVAL '1 hour', time) AS time, mean(usage_user) AS usage_user FROM cpu GROUP BY time_bucket(INTERVAL '1 hour', time), host. Flux (v2): from(bucket: "metrics") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "cpu") |> mean(). Telegraf input: [[inputs.cpu]] / [[inputs.mem]] / [[inputs.disk]] with [[outputs.influxdb_v2]]. Retention policy: Cloud Serverless sets retention in bucket settings; v2: influx bucket update --retention 30d. Claude Code generates InfluxDB write clients, SQL time series queries, downsampling pipelines, and Telegraf configurations.

CLAUDE.md for InfluxDB

## InfluxDB Stack
- Client: @influxdata/influxdb3-client (v3/Cloud Serverless) or @influxdata/influxdb-client (v2)
- Connect: new InfluxDBClient({ host: process.env.INFLUXDB_HOST!, token: process.env.INFLUXDB_TOKEN!, database: BUCKET })
- Write: client.write(lineProtocol) or client.writePoints([new Point(...).tag().floatField()])
- Query: for await (const row of client.query(sql)) — returns AsyncIterable<Record<string, unknown>>
- Line protocol: measurement,tag=val field=val nanosecond_timestamp
- Batching: collect 1000 points or 1s intervals before writing — reduces HTTP overhead

InfluxDB Client

// lib/influxdb/client.ts — InfluxDB v3 write and query client
import { InfluxDBClient, Point }  from "@influxdata/influxdb3-client"

const INFLUXDB_HOST     = process.env.INFLUXDB_HOST!    // e.g. https://us-east-1-1.aws.cloud2.influxdata.com
const INFLUXDB_TOKEN    = process.env.INFLUXDB_TOKEN!
const INFLUXDB_DATABASE = process.env.INFLUXDB_DATABASE ?? "metrics"

// Singleton client
const globalInflux = globalThis as unknown as { influxClient?: InfluxDBClient }

export function getClient(): InfluxDBClient {
  if (!globalInflux.influxClient) {
    globalInflux.influxClient = new InfluxDBClient({
      host:     INFLUXDB_HOST,
      token:    INFLUXDB_TOKEN,
      database: INFLUXDB_DATABASE,
    })
  }
  return globalInflux.influxClient
}

// ── Write helpers ──────────────────────────────────────────────────────────

export type MetricPoint = {
  measurement: string
  tags?:       Record<string, string>
  fields:      Record<string, number | string | boolean>
  timestamp?:  Date
}

/** Write a single metric point */
export async function writeMetric(metric: MetricPoint): Promise<void> {
  const client = getClient()
  const point  = new Point(metric.measurement)

  for (const [k, v] of Object.entries(metric.tags ?? {})) {
    point.tag(k, v)
  }

  for (const [k, v] of Object.entries(metric.fields)) {
    if (typeof v === "number") {
      Number.isInteger(v) ? point.intField(k, v) : point.floatField(k, v)
    } else if (typeof v === "boolean") {
      point.booleanField(k, v)
    } else {
      point.stringField(k, v)
    }
  }

  if (metric.timestamp) point.timestamp(metric.timestamp)

  await client.write(point)
}

/** Batch write for high-throughput scenarios */
export async function writeMetricsBatch(metrics: MetricPoint[]): Promise<void> {
  const client = getClient()
  const points = metrics.map((m) => {
    const p = new Point(m.measurement)
    for (const [k, v] of Object.entries(m.tags ?? {})) p.tag(k, v)
    for (const [k, v] of Object.entries(m.fields)) {
      if (typeof v === "number") {
        Number.isInteger(v) ? p.intField(k, v) : p.floatField(k, v)
      } else if (typeof v === "boolean") {
        p.booleanField(k, v)
      } else {
        p.stringField(k, v)
      }
    }
    if (m.timestamp) p.timestamp(m.timestamp)
    return p
  })

  await client.write(points)
}

// ── Query helpers ──────────────────────────────────────────────────────────

export type TimeSeriesRow = {
  time:        string
  measurement: string
  [field: string]: unknown
}

/** Execute a SQL query and collect all rows */
export async function queryRows<T extends TimeSeriesRow = TimeSeriesRow>(
  sql:     string,
  options: { database?: string } = {},
): Promise<T[]> {
  const client = getClient()
  const rows: T[] = []

  for await (const row of client.query(sql, { database: options.database ?? INFLUXDB_DATABASE })) {
    rows.push(row as T)
  }

  return rows
}

/** Time series aggregation — returns { time, value }[] */
export async function timeseries(options: {
  measurement:  string
  field:        string
  agg?:         "mean" | "sum" | "count" | "min" | "max" | "last"
  interval?:    string   // e.g. "5 minutes", "1 hour"
  where?:       string   // extra WHERE conditions
  lookback?:    string   // e.g. "24 hours", "7 days"
  tags?:        Record<string, string>
}): Promise<Array<{ time: string; value: number }>> {
  const {
    measurement, field,
    agg      = "mean",
    interval = "5 minutes",
    lookback = "1 hour",
    where,
    tags     = {},
  } = options

  const tagFilters = Object.entries(tags)
    .map(([k, v]) => `${k} = '${v}'`)
    .join(" AND ")

  const whereClause = [
    `time > now() - INTERVAL '${lookback}'`,
    tagFilters || null,
    where || null,
  ].filter(Boolean).join(" AND ")

  const sql = `
    SELECT
      time_bucket(INTERVAL '${interval}', time) AS time,
      ${agg}(${field})                           AS value
    FROM ${measurement}
    WHERE ${whereClause}
    GROUP BY 1
    ORDER BY 1 ASC
  `

  const rows = await queryRows<{ time: string; value: number }>(sql)
  return rows
}

Batch Write Buffer

// lib/influxdb/buffer.ts — buffered write for high-frequency metrics
import { writeMetricsBatch, type MetricPoint } from "./client"

export class MetricBuffer {
  private buffer:      MetricPoint[] = []
  private flushTimer:  ReturnType<typeof setTimeout> | null = null
  private readonly maxSize:      number
  private readonly flushInterval: number

  constructor(options: { maxSize?: number; flushIntervalMs?: number } = {}) {
    this.maxSize       = options.maxSize        ?? 1000
    this.flushInterval = options.flushIntervalMs ?? 1000
  }

  /** Add a metric to the buffer — flushes automatically */
  push(metric: MetricPoint): void {
    this.buffer.push(metric)

    if (this.buffer.length >= this.maxSize) {
      void this.flush()
      return
    }

    if (!this.flushTimer) {
      this.flushTimer = setTimeout(() => void this.flush(), this.flushInterval)
    }
  }

  /** Flush buffer to InfluxDB */
  async flush(): Promise<void> {
    if (this.flushTimer) {
      clearTimeout(this.flushTimer)
      this.flushTimer = null
    }

    if (this.buffer.length === 0) return

    const batch = this.buffer.splice(0, this.buffer.length)

    try {
      await writeMetricsBatch(batch)
    } catch (err) {
      console.error("[InfluxDB] Batch write failed:", err)
      // Re-add to buffer on failure (up to maxSize)
      if (this.buffer.length + batch.length <= this.maxSize * 2) {
        this.buffer.unshift(...batch)
      }
    }
  }
}

// Global buffer singleton
export const metricBuffer = new MetricBuffer({ maxSize: 500, flushIntervalMs: 2000 })

process.once("SIGTERM", () => metricBuffer.flush().catch(console.error))
process.once("SIGINT",  () => metricBuffer.flush().catch(console.error))

Next.js API Routes

// app/api/metrics/write/route.ts — ingest metrics from client/services
import { NextResponse }     from "next/server"
import { z }                from "zod"
import { metricBuffer }     from "@/lib/influxdb/buffer"
import { auth }             from "@/lib/auth"

const MetricSchema = z.object({
  measurement: z.string().max(64),
  tags:        z.record(z.string()).optional(),
  fields:      z.record(z.union([z.number(), z.string(), z.boolean()])),
  timestamp:   z.string().datetime().optional(),
})

const BatchSchema = z.array(MetricSchema).max(500)

export async function POST(req: Request) {
  const session = await auth()
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const body   = await req.json()
  const points = BatchSchema.parse(Array.isArray(body) ? body : [body])

  for (const p of points) {
    metricBuffer.push({
      ...p,
      timestamp: p.timestamp ? new Date(p.timestamp) : undefined,
      // Add user context as tags
      tags: { ...p.tags, userId: session.user.id },
    })
  }

  return NextResponse.json({ queued: points.length })
}

// app/api/metrics/query/route.ts — query time series data
import { timeseries } from "@/lib/influxdb/client"

export async function GET(req: Request) {
  const session = await auth()
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const url         = new URL(req.url)
  const measurement = url.searchParams.get("measurement") ?? "events"
  const field       = url.searchParams.get("field")       ?? "value"
  const agg         = (url.searchParams.get("agg")        ?? "mean") as "mean" | "sum" | "count"
  const interval    = url.searchParams.get("interval")    ?? "5 minutes"
  const lookback    = url.searchParams.get("lookback")    ?? "24 hours"

  const data = await timeseries({ measurement, field, agg, interval, lookback })
  return NextResponse.json({ data })
}

Telegraf Configuration

# telegraf.conf — collect system metrics and ship to InfluxDB v3
[agent]
  interval          = "10s"
  round_interval    = true
  metric_batch_size = 1000
  metric_buffer_limit = 10000
  flush_interval    = "10s"

# System inputs
[[inputs.cpu]]
  percpu         = false
  totalcpu       = true
  collect_cpu_time = false

[[inputs.mem]]

[[inputs.disk]]
  ignore_fs = ["tmpfs", "devtmpfs", "devfs", "iso9660", "overlay", "aufs", "squashfs"]

[[inputs.diskio]]

[[inputs.net]]
  interfaces = ["eth*", "en*"]

# HTTP endpoint metrics (scrape your /metrics route)
[[inputs.http]]
  urls    = ["http://localhost:3000/api/metrics?format=json"]
  method  = "GET"
  headers = { Authorization = "Bearer ${METRICS_TOKEN}" }
  data_format = "json"

# Output to InfluxDB v3
[[outputs.influxdb_v2]]
  urls         = ["${INFLUXDB_HOST}"]
  token        = "${INFLUXDB_TOKEN}"
  organization = ""    # not used in v3
  bucket       = "${INFLUXDB_DATABASE}"

For the Prometheus/Grafana alternative when needing pull-based metrics scraping across many services with a rich PromQL query language, Alertmanager for complex routing, and the broader Prometheus ecosystem (exporters for every system) — Prometheus is the standard for infrastructure monitoring while InfluxDB is optimized for write-heavy time series workloads like IoT sensor streams, high-frequency trading, and observability pipelines where you need compressed columnar storage and fast range queries. For the TimescaleDB alternative when needing a time series database with full PostgreSQL compatibility — relational joins, triggers, existing Postgres tooling (pgAdmin, Prisma, Drizzle), and PostGIS geography support — TimescaleDB extends PostgreSQL with hypertables while InfluxDB is a purpose-built TSDB with a line protocol optimized for high-cardinality metric streams. The Claude Skills 360 bundle includes InfluxDB skill sets covering write clients, SQL time series queries, and Telegraf configuration. Start with the free tier to try time series generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free