🗄️ Databases

InfluxDB

Time-Series Database

A database dedicated to time-series data. It processes millions of timestamp-based metrics, IoT sensor data, and monitoring logs per second, and supports powerful time-series analysis with the Flux query language.

📖 Detailed Explanation

InfluxDB is an open-source time series database (TSDB) developed by InfluxData. It is optimized for quickly storing and querying large volumes of time-ordered data, and is widely used for time-based data processing such as server monitoring, IoT sensor data, and financial market data.

The data model consists of a measurement (table), tags (indexed metadata), fields (actual values), and a timestamp. Tags are automatically indexed, enabling fast filtering, and fields store the actual measured values. This structure is optimized for the characteristics of time series data, making it far more efficient than a traditional RDBMS.

The Flux query language is a functional data scripting language introduced starting with InfluxDB 2.0. Unlike SQL, it processes data in a pipeline fashion and provides functions specialized for time series analysis (moving average, downsampling, forecasting, etc.) out of the box. InfluxQL from earlier versions is also still supported.

The TSM (Time-Structured Merge Tree) engine is the core storage engine of InfluxDB. It compresses time series data to save up to 90% of storage space and processes time-range-based queries very quickly. Old data can be deleted automatically with a Retention Policy.

The TICK stack is a complete monitoring solution consisting of Telegraf (data collection), InfluxDB (storage), Chronograf (visualization), and Kapacitor (alerting/processing). Starting with InfluxDB 2.0, these functions are integrated and provided as a single platform. Integration with Grafana is also very well supported.

💻 Code Example

# InfluxDB Python 클라이언트 예제
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
from datetime import datetime, timedelta
import random

# InfluxDB 연결 설정
url = "http://localhost:8086"
token = "your-token-here"
org = "your-org"
bucket = "metrics"

# 클라이언트 생성
client = InfluxDBClient(url=url, token=token, org=org)

# ============================================
# 데이터 쓰기
# ============================================
write_api = client.write_api(write_options=SYNCHRONOUS)

# Point 객체로 데이터 생성
point = Point("server_metrics") \
    .tag("host", "server-01") \
    .tag("region", "ap-northeast-2") \
    .field("cpu_usage", 45.5) \
    .field("memory_usage", 72.3) \
    .field("disk_io", 1250) \
    .time(datetime.utcnow())

# 단일 포인트 쓰기
write_api.write(bucket=bucket, record=point)
print("데이터 기록 완료")

# 배치 쓰기 (대량 데이터)
points = []
for i in range(100):
    p = Point("sensor_data") \
        .tag("sensor_id", f"sensor-{i % 10}") \
        .tag("location", "factory-a") \
        .field("temperature", 20 + random.random() * 10) \
        .field("humidity", 40 + random.random() * 20) \
        .time(datetime.utcnow() - timedelta(minutes=i))
    points.append(p)

write_api.write(bucket=bucket, record=points)
print(f"{len(points)}개 포인트 배치 기록 완료")


# ============================================
# 데이터 조회 (Flux 쿼리)
# ============================================
query_api = client.query_api()

# 최근 1시간 CPU 사용량 조회
query = '''
from(bucket: "metrics")
    |> range(start: -1h)
    |> filter(fn: (r) => r._measurement == "server_metrics")
    |> filter(fn: (r) => r._field == "cpu_usage")
    |> filter(fn: (r) => r.host == "server-01")
'''

tables = query_api.query(query)
for table in tables:
    for record in table.records:
        print(f"시간: {record.get_time()}, CPU: {record.get_value()}%")


# ============================================
# 집계 쿼리 - 5분 평균
# ============================================
aggregation_query = '''
from(bucket: "metrics")
    |> range(start: -24h)
    |> filter(fn: (r) => r._measurement == "server_metrics")
    |> filter(fn: (r) => r._field == "cpu_usage")
    |> aggregateWindow(every: 5m, fn: mean, createEmpty: false)
    |> yield(name: "5분 평균")
'''

result = query_api.query(aggregation_query)
print("\n5분 평균 CPU 사용량:")
for table in result:
    for record in table.records:
        print(f"  {record.get_time()}: {record.get_value():.2f}%")


# ============================================
# DataFrame으로 변환 (Pandas 연동)
# ============================================
df = query_api.query_data_frame('''
from(bucket: "metrics")
    |> range(start: -1h)
    |> filter(fn: (r) => r._measurement == "server_metrics")
    |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")
''')

print("\nDataFrame 결과:")
print(df.head())


# 리소스 정리
client.close()
// InfluxDB Node.js 클라이언트 예제
const { InfluxDB, Point } = require('@influxdata/influxdb-client');

// 연결 설정
const url = 'http://localhost:8086';
const token = 'your-token-here';
const org = 'your-org';
const bucket = 'metrics';

const client = new InfluxDB({ url, token });

// ============================================
// 데이터 쓰기
// ============================================
const writeApi = client.getWriteApi(org, bucket);

// 기본 태그 설정 (모든 포인트에 적용)
writeApi.useDefaultTags({ app: 'my-app', env: 'production' });

// Point 객체로 데이터 생성
const point = new Point('api_metrics')
    .tag('endpoint', '/api/users')
    .tag('method', 'GET')
    .floatField('response_time', 125.5)
    .intField('status_code', 200)
    .intField('request_size', 1024);

writeApi.writePoint(point);

// 여러 포인트 쓰기
for (let i = 0; i < 10; i++) {
    const p = new Point('request_log')
        .tag('service', 'user-service')
        .floatField('latency', Math.random() * 100)
        .intField('requests', Math.floor(Math.random() * 1000));
    writeApi.writePoint(p);
}

// 버퍼 플러시 및 완료 대기
writeApi.close()
    .then(() => console.log('데이터 기록 완료'))
    .catch(err => console.error('쓰기 오류:', err));


// ============================================
// 데이터 조회
// ============================================
const queryApi = client.getQueryApi(org);

const fluxQuery = `
from(bucket: "${bucket}")
    |> range(start: -1h)
    |> filter(fn: (r) => r._measurement == "api_metrics")
    |> filter(fn: (r) => r._field == "response_time")
`;

console.log('\n쿼리 결과:');
queryApi.queryRows(fluxQuery, {
    next: (row, tableMeta) => {
        const record = tableMeta.toObject(row);
        console.log(`  ${record._time}: ${record._value}ms (${record.endpoint})`);
    },
    error: (err) => console.error('쿼리 오류:', err),
    complete: () => console.log('쿼리 완료'),
});


// ============================================
// Promise 기반 조회
// ============================================
async function queryMetrics() {
    const query = `
    from(bucket: "${bucket}")
        |> range(start: -24h)
        |> filter(fn: (r) => r._measurement == "api_metrics")
        |> aggregateWindow(every: 1h, fn: mean)
        |> sort(columns: ["_time"], desc: true)
        |> limit(n: 10)
    `;

    const results = [];

    for await (const { values, tableMeta } of queryApi.iterateRows(query)) {
        const record = tableMeta.toObject(values);
        results.push({
            time: record._time,
            field: record._field,
            value: record._value,
            endpoint: record.endpoint
        });
    }

    return results;
}

queryMetrics()
    .then(data => {
        console.log('\n시간별 평균 응답시간:');
        data.forEach(r => console.log(`  ${r.time}: ${r.value?.toFixed(2)}ms`));
    });


// ============================================
// Health Check
// ============================================
const { HealthAPI } = require('@influxdata/influxdb-client-apis');

const healthApi = new HealthAPI(client);
healthApi.getHealth()
    .then(health => console.log('\nInfluxDB 상태:', health.status))
    .catch(err => console.error('Health check 실패:', err));
// ============================================
// Flux 쿼리 언어 기본
// ============================================

// 기본 조회 - 최근 1시간 데이터
from(bucket: "metrics")
    |> range(start: -1h)
    |> filter(fn: (r) => r._measurement == "server_metrics")

// 특정 필드와 태그 필터링
from(bucket: "metrics")
    |> range(start: -24h)
    |> filter(fn: (r) => r._measurement == "cpu")
    |> filter(fn: (r) => r._field == "usage_percent")
    |> filter(fn: (r) => r.host == "server-01" or r.host == "server-02")


// ============================================
// 집계 함수
// ============================================

// 윈도우 집계 - 5분 평균
from(bucket: "metrics")
    |> range(start: -6h)
    |> filter(fn: (r) => r._measurement == "cpu")
    |> aggregateWindow(every: 5m, fn: mean, createEmpty: false)

// 다양한 집계 함수
from(bucket: "metrics")
    |> range(start: -1h)
    |> filter(fn: (r) => r._field == "temperature")
    |> aggregateWindow(every: 10m, fn: max)  // max, min, sum, count, last

// 그룹별 집계
from(bucket: "metrics")
    |> range(start: -1h)
    |> filter(fn: (r) => r._measurement == "api_requests")
    |> group(columns: ["endpoint"])
    |> count()


// ============================================
// 다운샘플링 & 데이터 변환
// ============================================

// 다운샘플링 - 1분 데이터를 1시간으로
from(bucket: "raw_metrics")
    |> range(start: -7d)
    |> aggregateWindow(every: 1h, fn: mean)
    |> to(bucket: "downsampled_metrics")

// 이동 평균 (Moving Average)
from(bucket: "metrics")
    |> range(start: -2h)
    |> filter(fn: (r) => r._field == "cpu_usage")
    |> movingAverage(n: 5)

// 변화율 계산 (derivative)
from(bucket: "metrics")
    |> range(start: -1h)
    |> filter(fn: (r) => r._field == "requests_total")
    |> derivative(unit: 1m, nonNegative: true)


// ============================================
// 조인 & 피벗
// ============================================

// 두 measurement 조인
cpu = from(bucket: "metrics")
    |> range(start: -1h)
    |> filter(fn: (r) => r._measurement == "cpu")

memory = from(bucket: "metrics")
    |> range(start: -1h)
    |> filter(fn: (r) => r._measurement == "memory")

join(tables: {cpu: cpu, memory: memory}, on: ["_time", "host"])

// 피벗 - 필드를 컬럼으로 변환
from(bucket: "metrics")
    |> range(start: -1h)
    |> filter(fn: (r) => r._measurement == "server_metrics")
    |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")


// ============================================
// 알림 조건
// ============================================

// CPU 80% 이상 감지
from(bucket: "metrics")
    |> range(start: -5m)
    |> filter(fn: (r) => r._field == "cpu_usage")
    |> filter(fn: (r) => r._value > 80.0)
    |> count()
    |> map(fn: (r) => ({r with alert: r._value > 0}))

🗣️ Say It Like This in Practice

💬 In a monitoring system design meeting
"Let's store the server metrics in InfluxDB and visualize them with Grafana. It handles more than 100,000 metrics per second without any problem, and configuring the collection agent with Telegraf is simple too. If we set a Retention Policy so that data older than 7 days is deleted automatically, storage will be managed efficiently as well."
💬 In an IoT project technical review
"InfluxDB is a good fit for sensor data. It sorts automatically based on timestamps and has a high compression ratio, so storage costs are low. I think it would be good to tier it with downsampling, keeping the raw data for only 1 week and the 1-hour averages for 1 year."
💬 In a query optimization discussion
"In Flux queries, place filter as early as possible. The range and measurement filters need to come first so that the index is used. Also, if tag cardinality is too high, performance drops, so store things like UUIDs as fields, not as tags."

⚠️ Cautions & Best Practices

❌
Avoid high tag cardinality

Do not put unique values such as UUIDs or user IDs in tags. Tags are indexed and use a lot of memory. If cardinality is high, performance degrades sharply.

❌
Beware of indiscriminate series creation

The combination of measurement + tags creates a series. If the number of series exceeds several million, memory shortage and query performance degradation occur.

❌
Beware of bulk insertion of historical data

InfluxDB is optimized for writing the latest data. Inserting a large amount of old historical data can cause compaction load.

✅
InfluxDB Best Practices

Use a Retention Policy to delete data automatically, downsampling to compress long-term data, batch writes, and Continuous Query to implement real-time aggregation.

🔗 Related Terms

📚 Learn More