In the era of event-driven architecture and data pipelines, traditional monitoring often falls short. Knowing that a workflow completed is not enough; understanding how it behaved, where bottlenecks occurred, and what business metrics it generated is critical. Kestra, the open-source workflow orchestrator, provides a robust foundation for building observable systems. By leveraging custom metrics and distributed tracing, you can transform your orchestrations from black boxes into transparent, self-healing engines.
Why Observability Matters in Workflow Orchestration
Workflow orchestration involves complex dependencies, external API calls, data transformations, and conditional logic. Without deep observability, debugging failures becomes a guessing game. While Kestra offers built-in logging and execution details, adding custom metrics and tracing allows you to:
- Correlate workflow execution with business outcomes (e.g., revenue generated, users processed).
- Identify performance bottlenecks in specific tasks or API integrations.
- Send alerts based on business logic rather than just system health.
- Integrate with APM (Application Performance Monitoring) tools like Prometheus, Grafana, or Jaeger.
Implementing Custom Metrics with Kestra
Kestra supports exporting metrics via Prometheus. To add custom business metrics, you can use the metrics property in your task definitions. This allows you to emit counters, gauges, or histograms directly from your workflow steps.
For example, suppose you have a data ingestion workflow that processes user sign-ups. You want to track the number of successful sign-ups and the average processing time per user. You can define a Python task that emits these metrics:
id: user_ingestion_workflow
namespace: myteam
tasks:
- id: process_users
type: io.kestra.plugin.scripts.python.Script
run: |
import os
import json
import time
start_time = time.time()
data = json.load(open(os.environ['INPUT_FILE']))
success_count = 0
for user in data:
# Simulate processing
if user.get('active'):
success_count += 1
duration = time.time() - start_time
# Emit custom metrics
# Kestra automatically picks up metrics if structured correctly or via CLI
# For advanced cases, use the Kestra Python SDK or output metrics
print(f"METRIC: user_ingestion.success_count={success_count}")
print(f"METRIC: user_ingestion.processing_duration={duration:.2f}")
inputs:
- id: input_file
type: FILE
While the above example uses simple printing, in production, you would integrate with the Kestra Python SDK or use the metrics annotation in YAML for structured metric emission. Ensure your Prometheus configuration scrapes the Kestra metrics endpoint (/prometheus).
Adding Distributed Tracing for Deep Insights
When workflows interact with microservices or external APIs, distributed tracing becomes essential. Kestra integrates with OpenTelemetry, allowing you to propagate trace context across task boundaries.
To enable tracing, configure your Kestra instance with an OpenTelemetry exporter. Then, in your tasks, use the Kestra-provided trace ID to instrument your external calls. Here’s how you might do this in a JavaScript task that calls an external API:
tasks:
- id: call_external_api
type: io.kestra.plugin.scripts.js.Script
run: |
const axios = require('axios');
const traceId = process.env.KESTRA_TRACE_ID;
const spanId = process.env.KESTRA_SPAN_ID;
const headers = {
'X-Trace-Id': traceId,
'X-Span-Id': spanId
};
try {
const response = await axios.get('https://api.example.com/data', { headers });
console.log('API Response:', response.data);
} catch (error) {
console.error('API Call Failed:', error);
throw error;
}
enabled: true
By propagating KESTRA_TRACE_ID, you can link the Kestra workflow execution with the downstream service’s trace in your APM tool (e.g., Jaeger or Datadog). This provides end-to-end visibility into latency, errors, and dependencies.
Practical Example: Building a Self-Monitoring Data Pipeline
Consider a daily data pipeline that validates, transforms, and loads data into a warehouse. You want to monitor data quality metrics and ensure the pipeline is performant.
1. **Data Quality Metrics:** Use a Python task to calculate the number of null values, duplicate rows, and out-of-range entries. Emit these as custom metrics.
2. **Performance Tracing:** Measure the duration of each transformation step and log the trace ID.
3. **Alerting:** Configure Grafana alerts based on the custom metrics. For example, alert if data_quality.null_count > 100 or pipeline.duration_p95 > 300s.
tasks:
- id: validate_data
type: io.kestra.plugin.scripts.python.Script
run: |
import pandas as pd
df = pd.read_parquet('data.parquet')
null_count = df.isnull().sum().sum()
duplicate_count = df.duplicated().sum()
# Emit metrics
print(f"METRIC: data_quality.null_count={null_count}")
print(f"METRIC: data_quality.duplicate_count={duplicate_count}")
if null_count > 100:
raise ValueError("Too many null values detected")
Conclusion
Implementing custom metrics and distributed tracing in Kestra elevates your workflow orchestration from a simple execution engine to a fully observable platform. By integrating with Prometheus and OpenTelemetry, you gain the ability to monitor business outcomes, debug complex issues, and ensure high performance. As your workflows grow in complexity, observability becomes not just a best practice, but a necessity. Start small by adding a few key metrics and gradually expand your tracing coverage to achieve complete end-to-end visibility.