We are designing a high-frequency telemetry ingestion service using Apache Arrow Flight. The key components we need to address are:
- Schema management
- Flow control
- Storage integration
- Cost modeling
Let's break down each component and design accordingly.
-
Schema Management:
- Telemetry data can come from various sources with evolving schemas. We need to handle schema evolution (e.g., adding/removing columns, type changes).
- Apache Arrow Flight uses Apache Arrow schemas, which are self-describing. We can store the schema in a central schema registry or use a distributed metadata store.
- We can have a schema registry service that manages the schemas and assigns version IDs. The producer (data source) and consumer (ingestion service) must agree on the schema version.
- Alternatively, we can use the Arrow schema's built-in metadata to include a schema version and evolution rules.
-
Flow Control:
- Arrow Flight supports flow control at the protocol level. The client and server can negotiate the number of in-flight messages (or batches) to control the data flow.
- We can set limits on the memory usage per connection and globally. We can also implement backpressure by having the server signal when it's ready for more data.
- We can use the FlightDescriptor to include flow control parameters, or use the FlightInfo to negotiate.
-
Storage Integration:
- We need to store the ingested telemetry data efficiently for querying and analysis. Arrow Flight data can be stored in various formats (Parquet, Feather, etc.).
- We can have a storage layer that writes the incoming RecordBatches to a distributed file system (like HDFS, S3, or a local file system) in a columnar format (Parquet is recommended for its compression and partitioning support).
- We can also integrate with a database (like Apache Druid, ClickHouse, or even a data warehouse like Snowflake) if the use case requires low-latency queries.
- We might also consider a caching layer (like Redis) for recent data.
-
Cost Modeling:
- We need to estimate the cost of running the service. This includes:
a. Compute costs: for running the Flight servers and any data processing.
b. Storage costs: for storing the telemetry data (both raw and processed).
c. Network costs: for transferring data from the sources to the ingestion service (and possibly between components).
- We can model costs based on:
- Volume of data (ingested per day/month)
- Retention period (how long we keep raw and aggregated data)
- Query patterns (if we are also serving queries, we need to consider the cost of queries)
- Data compression ratios (Arrow and Parquet support compression, which reduces storage and network costs)
- We can use cloud provider pricing (like AWS, GCP, Azure) to estimate costs.
Now, let's design the system:
Overall Architecture:
Data Sources (producers) -> Arrow Flight Client -> Arrow Flight Server (Ingestion Service) -> Storage
We can have multiple Flight servers for scalability and fault tolerance. The Flight servers can be load balanced.
Steps:
-
Schema Management Design:
- We maintain a schema registry (could be a simple key-value store or a dedicated service). The schema is stored as an Arrow schema (bytes) and we assign a version.
- The producer must register the schema version it is using with the registry and get an ID. Then, when opening a Flight stream, it can include the schema version in the FlightDescriptor's command (or in a custom metadata field).
- The Flight server checks the schema version against the registry. If the schema is unknown, it can reject or try to fetch from the registry.
- The server can also store the schema version along with the data for future reference.
-
Flow Control Design:
- Use Arrow Flight's built-in flow control. The server can set the
max_message_size and max_row_count in the FlightDescriptor or in the handshake.
- We can also implement application-level flow control by having the server send a "ready" signal (as a control message) after it has processed a batch. However, Arrow Flight already has a way: the server can limit the number of in-flight messages by adjusting the window size (like in gRPC flow control).
- In practice, we can set the
max_flight_message_length and max_flight_data_per_message in the server configuration.
-
Storage Integration Design:
- The Flight server receives RecordBatches. We can write each RecordBatch (or group of RecordBatches) to a Parquet file. We can partition the data by:
- Date (year, month, day, hour)
- Source (producer ID)
- Schema version (if schemas are different and we want to keep them separate)
- We can also write to a streaming data store (like Kafka) for real-time processing, but the requirement is ingestion and storage.
- We can have a separate process that compacts small Parquet files into larger ones for efficient querying (like Hive style partitioning).
- Alternatively, we can write to a database that supports Arrow natively (like DataFusion's Flight SQL) but that might be more for querying.
-
Cost Modeling:
- We need to collect metrics:
- Ingested data size (compressed and uncompressed)
- Number of messages/batches
- Storage used (by partition and retention)
- Network I/O (bytes in/out)
- Then we can use cloud pricing to estimate costs. For example, on AWS S3:
- Storage cost: $0.023 per GB per month (for standard storage in us-east-1 as of 2023, but check current)
- Request cost: PUT requests (ingestion) cost $0.005 per 1000 requests (for S3 standard)
Implementation Considerations:
- We can use the Apache Arrow Flight C++ library, or the Java/Python implementations. For high performance, C++ is recommended, but Java and Python are also viable.
- The Flight server should be designed to handle multiple concurrent streams. We can use a thread pool or async I/O.
- We need to handle failures: if the storage write fails, we should either retry or buffer and retry later (but be cautious of memory usage). We can also have a dead-letter queue for failed batches.
- Security: Flight supports TLS and authentication (like Kerberos, JWT). We should configure appropriately.
Example Flow:
- Producer registers schema (if not already) with the schema registry and gets a schema version ID.
- Producer opens a Flight stream to the ingestion service, providing the schema version in the command (or in the FlightDescriptor's options).
- Server checks the schema version and retrieves the schema from the registry (or rejects if invalid).
- Server and client negotiate flow control parameters (max message size, etc.).
- Producer starts sending RecordBatches. The server writes each batch to a temporary buffer (or directly to storage if it's safe) and acknowledges (or not, depending on the flow control).
- The server periodically flushes the buffers to Parquet files (based on time, size, or number of batches) and closes the file, then moves to the next.
- The server can also store metadata about the written files (like file path, schema version, number of rows, size) in a metastore (like a database) for later querying.
Cost Modeling Example:
Let's assume:
- Ingest 1 TB of data per day (uncompressed). With Parquet compression (say 50% reduction), that's 500 GB per day.
- Retention: 30 days of raw data, and 365 days of aggregated data (but we only store raw for 30 days).
- Storage cost: 0.023perGBpermonth.Rawstora345 per month.
- Compute: Suppose we use 4 m5.xlarge (4 vCPU, 16 GB each) for the Flight servers at 552.96 per month.
- Network: Assume all data is coming from within the same region (free) and we don't serve queries from this storage (so no egress). But if we do, we need to account for egress.
We can adjust the numbers based on actual usage.
This is a high-level design. We need to consider more details for production:
- Monitoring and logging.
- Alerting on ingestion lag or errors.
- Auto-scaling of Flight servers based on load.
- Schema evolution: how to handle changes? We can use Arrow's schema evolution (likeadding a column with a default value) but the consumer (query engine) must be able to handle multiple schemas.
Let me know if you need more details on any specific part.
I'll design a comprehensive high-frequency telemetry ingestion service using Apache Arrow Flight, addressing all your requirements.
Architecture Overview
┌─────────────┐ ┌──────────────────┐ ┌──────────────┐
│ Telemetry │───▶│ Arrow Flight │───▶│ Columnar │
│ Sources │ │ Server │ │ Storage │
│ (IoT, Apps, │ │ (Ingestion) │ │ (Parquet/ │
│ Vehicles) │ │ │ │ Iceberg) │
└─────────────┘ └──────────────────┘ └──────────────┘
│ │ │ │
▼ ▼ ▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ Schema Registry │ │ Metastore │
│ & Evolution │ │ (Hive/Glue) │
└──────────────────┘ └──────────────────┘
│
▼
┌──────────────────┐
│ Monitoring & │
│ Cost Tracking │
└──────────────────┘
1. Schema Management
Schema Registry Design
# Schema Registry Service using etcd/ZooKeeper
class SchemaRegistry:
def __init__(self):
self.schemas = {} # versioned schemas
self.compatibility = {
'BACKWARD': True, # New reader can read old data
'FORWARD': False, # Old reader can read new data
'FULL': False # Both directions
}
def register_schema(self, subject: str, schema: pa.Schema,
compatibility: str = 'BACKWARD') -> int:
"""Register new schema version with compatibility rules"""
version = self._next_version(subject)
self._validate_compatibility(subject, schema, compatibility)
self.schemas[(subject, version)] = {
'schema': schema,
'timestamp': datetime.utcnow(),
'compatibility': compatibility
}
return version
def get_schema(self, subject: str, version: int) -> pa.Schema:
"""Retrieve schema for specific version"""
return self.schemas[(subject, version)]['schema']
def get_latest_schema(self, subject: str) -> Tuple[pa.Schema, int]:
"""Get latest schema version"""
# ... implementation
def check_compatibility(self, subject: str, new_schema: pa.Schema) -> bool:
"""Validate against compatibility rules"""
# ... compatibility checking logic
Schema Evolution Strategy
# Schema evolution handlers
class SchemaEvolution:
@staticmethod
def evolve_data(old_schema: pa.Schema, new_schema: pa.Schema,
data: pa.RecordBatch) -> pa.RecordBatch:
"""Transform data between schema versions"""
# Column additions (with default values)
# Column removals (ignore)
# Type promotions (safe conversions)
# Field renames (metadata mapping)
pass
# Arrow's built-in schema evolution:
# - pa.Schema.union() for compatible schemas
# - Custom projection for incompatible changes
Flight Descriptor with Schema Version
// Java Flight Server implementation
public class TelemetryFlightServer {
public FlightDescriptor getFlightDescriptor() {
return FlightDescriptor.command(
"telemetry_ingest".getBytes(),
new TelemetryMetadata(
schemaRegistryId, // Schema version ID
sourceId, // Device/source ID
timestamp, // Event time
checksum // Data integrity
).serialize()
);
}
}
2. Flow Control Mechanism
Multi-Level Flow Control
class FlowControl:
def __init__(self):
# Protocol-level (Arrow Flight built-in)
self.max_messages_per_stream = 1000
self.max_row_count_per_message = 100_000
self.max_data_per_message = 64 * 1024 * 1024 # 64MB
# Application-level
self.global_concurrent_streams = 1000
self.per_source_quota = {} # Dynamic per-source limits
self.memory_watermarks = {
'high': 0.8, # 80% heap usage
'low': 0.6 # 60% heap usage
}
async def backpressure_signal(self, stream_id: str):
"""Signal client to slow down"""
# Send control message via Flight's DoPut
# Implement window-based flow control
pass
def adjust_quotas(self, source_stats: Dict):
"""Dynamic quota adjustment based on SLA"""
if source_stats['latency_p99'] > SLA_THRESHOLD:
self.per_source_quota[source_stats['id']] *= 0.8
Arrow Flight Flow Control Configuration
// Go Flight Server configuration
server := flight.NewServer()
server.SetMaxMessageSize(64 * 1024 * 1024) // 64MB max message
server.SetMaxRowCount(100000) // Max rows per batch
server.SetMaxConcurrentStreams(1000) // Max parallel streams
// Custom middleware for per-source throttling
server.RegisterMiddleWare(&ThrottleMiddleware{
tokenBucket: utils.NewTokenBucket(rate.Limit(10000), 10000),
})
3. Storage Integration
Multi-Tier Storage Architecture
class StorageIntegration:
def __init__(self):
self.hot_storage = DeltaLake() # Recent data (0-7 days)
self.warm_storage = Iceberg() # Historical (8-90 days)
self.cold_storage = ParquetOnS3() # Archive (90+ days)
async def write_batch(self, batch: pa.RecordBatch,
schema_version: int, source: str):
"""Write batch to appropriate storage tier"""
# 1. Write to hot storage (Delta Lake for ACID)
await self.hot_storage.write(
batch,
partition_by=['date', 'source_id', 'schema_version']
)
# 2. Async compaction to warm storage (Iceberg)
asyncio.create_task(self.compaction_pipeline(batch))
# 3. metadata tracking
await self.metastore.register_file(
path=batch.file_path,
schema_version=schema_version,
row_count=batch.num_rows,
size_bytes=batch.nbytes,
min_timestamp=batch.min('timestamp'),
max_timestamp=batch.max('timestamp')
)
Storage Layer Recommendations
| Tier | Format | Retention | Use Case |
|---|
| Hot | Delta Lake | 0-7 days | Real-time queries, point lookups |
| Warm | Apache Iceberg | 8-90 days | Batch analytics, time series |
| Cold | Parquet + Zstd | 90+ days | Compliance, rare access |
Compaction Strategy
-- Iceberg table with automatic compaction
CREATE TABLE telemetry (
timestamp TIMESTAMP,
device_id STRING,
metrics STRUCT<temp:DOUBLE, humidity:INT>,
schema_version INT
) PARTITIONED BY (days(timestamp), device_id)
WITH (
'format' = 'parquet',
'compression' = 'zstd(level=3)',
'write.metadata.compression-codec' = 'gzip'
);
-- Optimize daily
CALL iceberg.system.rewrite_data_files(
table => 'telemetry',
options => {
'max-file-size-bytes': '134217728', -- 128MB
'min-file-size-bytes': '67108864' -- 64MB
}
);
4. Cost Modeling
Cost Components
class CostModel:
def __init__(self, cloud_provider: str, region: str):
self.pricing = {
'aws': {
's3_storage': 0.023, # $/GB/month
's3_put': 0.005, # $/1000 requests
'compute': { # EC2/Fargate pricing
'm5.xlarge': 0.192, # $/hour
'c5.2xlarge': 0.34
},
'data_transfer': {
'in': 0, # Free ingress
'out': 0.09 # $/GB (first 10TB)
}
},
'gcp': { ... }
}
def estimate_monthly_cost(self,
daily_ingest_tb: float,
retention_days: int,
query_volume_tb: float) -> Dict:
"""Estimate monthly operational costs"""
# 1. Storage costs (multi-tier)
storage_gb = daily_ingest_tb * 1024 * retention_days
storage_cost = storage_gb * self.pricing['s3_storage'] / 30
# 2. Write request costs
daily_records = daily_ingest_tb * 1e12 / 500 # Avg 500 bytes/record
put_requests = daily_records * 30
request_cost = (put_requests / 1000) * self.pricing['s3_put']
# 3. Compute costs (Flight servers)
# Assume 4 c5.2xlarge for ingestion, 2 m5.xlarge for compaction
compute_cost = (4 * 0.34 + 2 * 0.192) * 24 * 30
# 4. Network egress (if queries served to external)
egress_cost = query_volume_tb * self.pricing['data_transfer']['out']
return {
'storage': storage_cost,
'requests': request_cost,
'compute': compute_cost,
'network_egress': egress_cost,
'total': storage_cost + request_cost + compute_cost + egress_cost
}
Optimization Strategies
1. Compression Trade-offs
COMPRESSION_OPTIONS = {
'zstd_level_3': {
'ratio': 3.5, # 3.5x compression
'speed': 'fast',
'cost_impact': -0.15 # Reduces storage but adds CPU
},
'snappy': {
'ratio': 2.0,
'speed': 'very fast',
'cost_impact': -0.05
},
'uncompressed': {
'ratio': 1.0,
'speed': 'instant',
'cost_impact': 0
}
}
2. Tiered Storage Cost Savings
| Policy | Storage | Compute | Query Cost |
|---|
| Hot 7 days | $0.23/GB/mo | High (Low latency) | Low |
| Warm 90 days | $0.023/GB/mo | Medium | Medium |
| Cold 3 years | $0.004/GB/mo | Low (Async) | High |
Example Calculation:
- 10 TB/day ingestion × 365 days = 3.65 PB/year
- Without tiering: 3,650 TB × 0.023=∗∗83,950/month**
- With 7/90/1095 tiering: $15,200/month (82% savings)
5. Complete Implementation Sketch
Flight Server Implementation
import pyarrow as pa
import pyarrow.flight as flight
class TelemetryFlightServer(flight.FlightServerBase):
def __init__(self, location, schema_registry, storage):
super().__init__(location)
self.schema_registry = schema_registry
self.storage = storage
self.flow_control = FlowControl()
self.active_streams = {}
def do_put(self, context, descriptor, reader, writer):
"""Main ingestion endpoint"""
# 1. Parse descriptor for schema version
metadata = TelemetryMetadata.parse(descriptor.command)
schema = self.schema_registry.get_schema(
metadata.subject,
metadata.version
)
# 2. Check flow control
if not self.flow_control.can_accept_stream(metadata.source_id):
raise flight.FlightUnavailableError("Flow control limit reached")
# 3. Stream processing with backpressure
batches = []
try:
while True:
batch = reader.read_chunk()
if batch is None:
break
# 4. Schema evolution if needed
if batch.schema != schema:
batch = SchemaEvolution.evolve_data(
batch.schema, schema, batch
)
batches.append(batch)
# 5. Periodic flush to storage
if len(batches) >= self.flush_batch_size:
await self._flush_batches(batches, metadata)
batches = []
# 6. Send backpressure signal if needed
if self.flow_control.needs_backpressure():
writer.write_control(
flight.CoordinatedRequestMetadata()
.set_key("backpressure", "1")
)
finally:
# Flush remaining
if batches:
await self._flush_batches(batches, metadata)
self.flow_control.release_stream(metadata.source_id)
async def _flush_batches(self, batches, metadata):
"""Write batches to storage"""
combined = pa.Table.from_batches(batches)
await self.storage.write_batch(
combined.to_batches()[0], # Or handle multiple
metadata.version,
metadata.source_id
)
Client Implementation
class TelemetryClient:
def __init__(self, flight_uri, schema_registry):
self.flight = flight.FlightClient(flight_uri)
self.schema_registry = schema_registry
async def send_telemetry(self, source_id: str, data: pa.Table):
"""Send telemetry to Flight server"""
# 1. Get current schema version for source
schema_version = await self.schema_registry.get_version(
f"telemetry.{source_id}"
)
schema = self.schema_registry.get_schema(schema_version)
# 2. Ensure data matches schema (or evolve)
if data.schema != schema:
data = data.cast(schema) # Safe cast
# 3. Prepare Flight descriptor
descriptor = flight.FlightDescriptor.command(
TelemetryMetadata(
subject=f"telemetry.{source_id}",
version=schema_version,
source_id=source_id,
timestamp=datetime.utcnow()
).serialize()
)
# 4. Get flight info (endpoint)
info = self.flight.get_flight_info(descriptor)
endpoint = info.endpoints[0]
# 5. Stream data with flow control
writer, reader = self.flight.do_put(endpoint, data.schema)
# Write in chunks respecting server's max message size
for batch in data.to_batches(max_chunksize=10000):
writer.write_batch(batch)
# Handle backpressure from server
if reader.next():
control = reader.read_control()
if control and "backpressure" in control:
await asyncio.sleep(0.1) # Adaptive backoff
writer.done_writing()
reader.read_all() # Wait for acknowledgment
6. Monitoring & Observability
Key Metrics
metrics:
ingestion:
- flight_active_streams
- flight_messages_per_second
- batch_size_p50/p99
- schema_mismatch_rate
storage:
- write_latency_p99
- compaction_queue_depth
- storage_tier_utilization
flow_control:
- backpressure_events
- quota_violations
- memory_usage_per_source
cost:
- cost_per_gb_ingested
- storage_cost_by_tier
- compute_efficiency (records/CPU-second)
Grafana Dashboard Example
# Prometheus metrics exposition
class TelemetryMetrics:
def __init__(self):
self.ingestion_rate = Gauge(
'telemetry_ingestion_rate',
'Records per second',
['source', 'schema_version']
)
self.cost_gb = Gauge(
'storage_cost_per_gb',
'Cost per GB stored'
)
7. Deployment & Scaling
Kubernetes Deployment
# flight-server deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: flight-server
spec:
replicas: 3
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
spec:
containers:
- name: flight
image: arrow-flight:latest
ports:
- containerPort: 2815
resources:
limits:
memory: "8Gi"
cpu: "2"
requests:
memory: "4Gi"
cpu: "1"
env:
- name: FLIGHT_MAX_CONCURRENT_STREAMS
value: "1000"
- name: SCHEMA_REGISTRY_URL
value: "etcd://schema-registry:2379"
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: flight-data-pvc
# HPA for autoscaling
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
spec:
metrics:
- type: Pods
pods:
metric:
name: flight_active_streams
target:
type: AverageValue
averageValue: 500
8. Schema Evolution Best Practices
Compatibility Matrix
| Change Type | BACKWARD | FORWARD | FULL |
|----------------------|----------|---------|------|
| Add column (nullable)| ✓ | ✓ | ✓ |
| Add column (default) | ✓ | ✓ | ✓ |
| Remove column | ✗ | ✓ | ✗ |
| Type widen (int→long)| ✓ | ✗ | ✗ |
| Type narrow (long→int)| ✗ | ✗ | ✗ |
| Field rename | ✗ | ✗ | ✗ |
Migration Strategy
-- 1. Add new columns as nullable
ALTER TABLE telemetry ADD COLUMN new_metric DOUBLE;
-- 2. Backfill old data (if needed)
UPDATE telemetry SET new_metric = old_metric * 1.1;
-- 3. Deploy new version that reads both old and new
-- 4. Remove old column after grace period
ALTER TABLE telemetry DROP COLUMN old_metric;
Key Decisions & Trade-offs
-
Arrow Flight over REST/HTTP2:
- ✅ 10-100x throughput improvement
- ✅ Zero-copy columnar transfers
- ❌ Less tooling ecosystem
-
Schema Registry Choice:
- Confluent Schema Registry: Kafka-native, good for event streaming
- etcd/ZooKeeper: Simple, fast, for service discovery
- Custom with S3 backend: Cost-effective, durable
-
Storage Format:
- Parquet: Universal, good compression
- Arrow IPC: Faster for intermediate processing
- ORC: Better for Hive/Enterprise
-
Flow Control Strategy:
- Protocol-level (Flight) + Application-level (token bucket) = Best of both
- Reactive (backpressure) + Proactive (quotas)
-
Cost Optimization:
- Compression: Zstd level 3 (best ratio/speed)
- Tiering: 7/90/1095 policy saves 70-80%
- Spot instances: For non-critical compaction jobs
Recommended Stack
| Component | Technology | Justification |
|---|
| Flight Server | C++ (native) or Java | Best performance, mature implementations |
| Schema Registry | etcd + custom service | Fast, simple, suitable for service config |
| Hot Storage | Delta Lake on SSD | ACID, time travel, update/delete support |
| Warm Storage | Apache Iceberg on HDD | Partition evolution, hidden partitioning |
| Cold Storage | S3 + Parquet + Zstd | Cheapest, 12x 9s durability |
| Metadata Store | AWS Glue / Hive Metastore | Query federation, partition pruning |
| Monitoring | Prometheus + Grafana | Industry standard, rich integrations |
| Alerting | PagerDuty + Opsgenie | Production-ready incident management |
| Deployment | Kubernetes + Helm | Scalable, observable, self-healing |
Production Checklist
This design provides a scalable, cost-effective telemetry ingestion pipeline leveraging Arrow Flight's performance while addressing real-world concerns of schema evolution, flow control, storage optimization, and cost management.