In modern network observability architectures, data silos often hinder the ability of different microservices to make timely decisions. A security service might need immediate access to calculated latency baselines that a traffic analysis service has already computed. Building a real-time feature store using Redis solves this problem by providing a low-latency, in-memory cache for preprocessed metrics. This lab guides you through constructing such a system, ensuring your network services can share state efficiently without complex database queries.
Prerequisites and Environment Setup
Before beginning, ensure you have a Linux or macOS environment with Python 3.9+ installed. You will need redis-cli for command-line interaction and the Python packages redis, pandas, and fastapi. Install these dependencies using pip:
pip install redis pandas fastapi uvicorn
Verify that Redis is running locally on the default port 6379:
redis-cli ping
# Expected output: PONG
If you do not have a local Redis instance, you can use Docker to spin one up quickly:
docker run -d -p 6379:6379 redis:latest
Designing the Feature Schema
A feature store requires a consistent schema so that different services interpret data identically. For this network metrics scenario, we will define features such as avg_latency_ms, packet_loss_rate, and active_connections. These represent preprocessed values derived from raw flow logs.
Create a Python file named feature_definitions.py to standardize these definitions:
FEATURES = {
"avg_latency_ms": {"type": "float", "unit": "milliseconds"},
"packet_loss_rate": {"type": "float", "unit": "percentage"},
"active_connections": {"type": "int"}
}
This dictionary acts as your contract. Any microservice writing to or reading from the feature store must adhere to these keys and types. This prevents type errors downstream in machine learning models or alerting logic.
Step 1: Ingesting and Preprocessing Raw Metrics
The first microservice role is the “Ingestion Service.” It receives raw network packets or flow data, calculates aggregates, and pushes them into Redis. Imagine a script simulating incoming sensor data every second.
import redis
import random
import time
r = redis.Redis(host='localhost', port=6379, db=0)
def generate_and_store_metrics():
timestamp = int(time.time() * 1000) # Milliseconds for precision
# Simulate raw data calculation
latency = random.uniform(10.0, 200.0)
loss_rate = random.uniform(0.0, 5.0)
conn_count = random.randint(100, 500)
# Store as a hash key where field names match our feature schema
r.hset(f"feature:network:{timestamp}", mapping={
"avg_latency_ms": latency,
"packet_loss_rate": loss_rate,
"active_connections": conn_count
})
# Run this function periodically in a real app (e.g., via Celery or cron)
Expected Result: Running this function populates Redis with hash keys. You can verify the data exists:
redis-cli HGETALL "feature:network:1678890000000"
Step 2: Serving Features to Microservices
The second role is the “Feature Retrieval Service.” Instead of querying a heavy SQL database, this service fetches precomputed values from Redis. This is critical for real-time inference where latency must be under 10 milliseconds.
Imagine an API endpoint that accepts a timestamp and returns the latest available features:
from fastapi import FastAPI
import redis
app = FastAPI()
r = redis.Redis(host='localhost', port=6379, db=0)
@app.get("/features/{timestamp}")
def get_features(timestamp):
key = f"feature:network:{timestamp}"
features = r.hgetall(key)
if not features:
return {"error": "No data found for timestamp"}
return dict(features)
Verification: Access http://localhost:8000/features/1678890000000. The response should contain JSON matching your schema. If the key is missing, the ingestion step failed or the timestamp is too old.
Step 3: Implementing Expiration and Consistency
Storing raw metrics indefinitely fills memory. In a real-world scenario, you must implement Time-To-Live (TTL) to manage memory usage while keeping data fresh enough for model training windows.
Modify your ingestion logic to set an expiration on the hash key:
r.expire(f"feature:network:{timestamp}", 60) # Expires in 60 seconds
Common Error: If you clear Redis manually (FLUSHALL), you lose all feature data immediately. Always use KEYS * to inspect what exists before clearing. In production, use a dedicated Redis database (e.g., db=2) for features to separate them from session data or caching layers.
Step 4: Debugging and Monitoring
When deploying in a microservices architecture, debugging connectivity issues is common. If a service returns “No data found,” check network firewalls between the application container and Redis. Also, monitor memory usage with redis-cli INFO memory.
If latency spikes occur, it may indicate the feature store is approaching its memory limit. Consider partitioning features by time range (e.g., feature:network:hourly) if a single timestamp approach becomes insufficient for long-term retention.
Student Practice Task
To solidify your understanding, create two separate Python scripts in different directories. One script simulates the ingestion service; the other simulates a machine learning model that fetches features to predict network congestion.
1. Run the ingestion script to populate Redis.
2. Run the model script which queries the FastAPI endpoint.
3. Intentionally introduce a 5-second delay in one script and observe how the feature store decouples their execution times.
Industry Application Checklist
For industry practitioners, here is a checklist for deploying this pattern:
– [ ] Define a strict schema for all features to ensure cross-service compatibility.
– [ ] Set appropriate TTL values based on model retraining windows (e.g., 5 minutes for real-time fraud detection).
– [ ] Use Redis Sentinel or Cluster mode for high availability in production.
– [ ] Implement background jobs to backfill historical features if they were missed during ingestion.
– [ ] Verify policy terms regarding data retention and privacy compliance (GDPR, CCPA) before storing PII-derived metrics.
Conclusion
Implementing a real-time feature store with Redis bridges the gap between heavy data processing pipelines and low-latency microservices. By precomputing network metrics like latency and packet loss and storing them in hashed keys, you enable diverse services to access consistent, up-to-date data instantly. This architecture supports reproducible mini-projects, facilitates model evaluation on fresh data, and scales well as your observability platform grows. Remember to always validate your assumptions about memory limits and expiration policies to ensure system stability.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

