Cut API latency by 50-90% with Adaptive Anticipatory Approximation
Project description
LatencyZero - Adaptive Anticipatory Approximation (Aยณ)
Cut API latency by 50-90% with predictive approximation and guaranteed correctness.
๐ What is LatencyZero?
LatencyZero is a drop-in middleware that sits in front of expensive APIs, databases, or AI models and delivers instant responses through intelligent approximation.
Key Features
- โก 50-90% latency reduction - Most queries return in <10ms
- ๐ฏ Guaranteed correctness - Confidence-based fallback ensures accuracy
- ๐ง Drop-in integration - Single decorator, no infrastructure changes
- ๐ Real-time analytics - Full observability into performance gains
- ๐ Progressive refinement - Return fast, improve in background
๐ฆ Installation
1. Install the SDK
pip install latencyzero
Or install from source:
git clone https://github.com/latencyzero/latencyzero
cd latencyzero
pip install -e .
2. Start the Gateway Service
# Install gateway dependencies
pip install -r requirements.txt
# Start the gateway
cd gateway
python server.py
The gateway will start on http://localhost:8080
3. (Optional) Start Redis
For production use, connect Redis for persistent storage:
# Using Docker
docker run -d -p 6379:6379 redis:latest
# Or install locally
brew install redis # macOS
sudo apt-get install redis # Ubuntu
๐ฏ Quick Start
from latencyzero import a3
# Just add the decorator to any expensive function
@a3(tolerance=0.02)
def expensive_api_call(input_data):
# Your expensive computation here
return model.run(input_data)
# First call: ~2000ms (exact computation)
result = expensive_api_call("user query")
# Second call: ~10ms (approximation) โก
result = expensive_api_call("user query")
That's it! No infrastructure changes, no refactoring, no lock-in.
๐ Usage Examples
Example 1: OpenAI API Acceleration
from latencyzero import a3
import openai
@a3(tolerance=0.02)
def call_openai(prompt):
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
# First call: ~2000ms
answer = call_openai("What is Python?")
# Repeated call: ~10ms โก
answer = call_openai("What is Python?")
Example 2: Database Query Acceleration
@a3(tolerance=0.05)
def get_user_analytics(user_id):
# Expensive database aggregation
return db.execute("""
SELECT user_id,
COUNT(*) as total_orders,
SUM(amount) as total_revenue,
AVG(rating) as avg_rating
FROM orders
WHERE user_id = ?
GROUP BY user_id
""", user_id)
# First call: ~500ms
stats = get_user_analytics("user_123")
# Repeated call: ~5ms โก
stats = get_user_analytics("user_123")
Example 3: ML Model Inference
@a3(tolerance=0.01) # Stricter tolerance for ML
def predict_sentiment(text):
# Expensive ML model inference
inputs = tokenizer(text, return_tensors="pt")
outputs = model(**inputs)
return torch.softmax(outputs.logits, dim=1).tolist()
# First call: ~800ms
sentiment = predict_sentiment("This product is amazing!")
# Repeated call: ~8ms โก
sentiment = predict_sentiment("This product is amazing!")
๐ง Configuration
Configure the SDK
from latencyzero import configure
configure(
gateway_url="http://localhost:8080",
api_key="your_api_key", # Optional
timeout=0.1, # 100ms timeout for approximation
enable_metrics=True
)
Environment Variables
export LATENCYZERO_GATEWAY_URL="http://localhost:8080"
export LATENCYZERO_API_KEY="your_api_key"
export LATENCYZERO_TIMEOUT="0.1"
Decorator Options
@a3(
tolerance=0.02, # Max error rate (2%)
enable_refinement=True, # Background refinement
fallback_on_error=True # Safe fallback on errors
)
def my_function(input):
...
๐ Monitoring & Statistics
# Get statistics for a decorated function
stats = expensive_api_call.get_stats()
print(f"Total requests: {stats['total_requests']}")
print(f"Cache hits: {stats['cache_hits']}")
print(f"Hit rate: {stats['hit_rate']*100:.1f}%")
print(f"Latency improvement: {stats['latency_improvement']:.1f}%")
# Temporarily disable Aยณ for a function
expensive_api_call.disable()
# Re-enable
expensive_api_call.enable()
๐๏ธ Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Your Application โ
โ โ
โ @a3(tolerance=0.02) โ
โ def expensive_api(): โ
โ return expensive_computation() โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LatencyZero Gateway (Port 8080) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ 1. Prediction Engine โ โ
โ โ - Pattern detection โ โ
โ โ - Frequency analysis โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ 2. Approximation Store (Redis) โ โ
โ โ - Fast cached results โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ 3. Confidence Evaluator โ โ
โ โ - Age penalty โ โ
โ โ - Hit count confidence โ โ
โ โ - Historical accuracy โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ 4. Refinement Worker โ โ
โ โ - Background improvements โ โ
โ โ - Async execution โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ๏ธ How It Works
-
First Call (Exact)
- Query arrives at gateway
- No approximation available
- Execute exact computation
- Store result for future use
- Return to caller (~2000ms)
-
Subsequent Calls (Approximate)
- Query arrives at gateway
- Check approximation store
- Evaluate confidence score
- If confidence > threshold: return cached result (~10ms) โก
- If confidence < threshold: execute exact computation
- Background worker refines result
-
Confidence Evaluation
- Age of cached result (fresher = higher confidence)
- Hit count (more hits = higher confidence)
- Historical accuracy (track per function)
- Execution time variance (stable = higher confidence)
๐ฌ Running the Demo
# Terminal 1: Start the gateway
cd gateway
python server.py
# Terminal 2: Run the demo
cd examples
python demo.py
Expected output:
๐๐๐ LatencyZero Demo ๐๐๐
DEMO 1: Basic Usage
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1๏ธโฃ First call (exact computation):
โฑ๏ธ Latency: 2043.21ms
2๏ธโฃ Second call (approximation):
โก Latency: 12.34ms
๐ฏ Latency improvement: 99.4%
โก Speedup: 165.6x faster
๐งช Testing
# Run tests
pytest tests/
# Run with coverage
pytest --cov=latencyzero tests/
๐ Performance Benchmarks
| Use Case | First Call | Cached Call | Improvement |
|---|---|---|---|
| OpenAI API | ~2000ms | ~10ms | 99.5% |
| Database Query | ~500ms | ~5ms | 99.0% |
| ML Inference | ~800ms | ~8ms | 99.0% |
| REST API | ~1000ms | ~10ms | 99.0% |
๐ ๏ธ Production Deployment
Using Docker
# Build gateway image
docker build -t latencyzero-gateway ./gateway
# Run with Redis
docker-compose up -d
Docker Compose
version: '3.8'
services:
gateway:
image: latencyzero-gateway
ports:
- "8080:8080"
environment:
- REDIS_URL=redis://redis:6379
depends_on:
- redis
redis:
image: redis:latest
ports:
- "6379:6379"
๐ Security
- API Key Authentication: Protect your gateway with API keys
- Rate Limiting: Built-in rate limiting per client
- Data Encryption: All data encrypted in transit
- Private Deployment: Deploy on-premises or in your VPC
๐ API Reference
Client API
# Configure client
configure(gateway_url, api_key, timeout, enable_metrics)
# Decorator
@a3(tolerance, enable_refinement, fallback_on_error)
# Statistics
function.get_stats()
function.disable()
function.enable()
Gateway API
GET / # Health check
GET /api/v1/approximate # Get approximation
POST /api/v1/store # Store result
GET /api/v1/stats # Gateway statistics
GET /api/v1/predictions/{fn} # Get predictions
POST /api/v1/admin/clear # Clear cache (admin)
๐ค Contributing
We welcome contributions! Please see CONTRIBUTING.md for details.
๐ License
MIT License - see LICENSE for details
๐ Roadmap
- Go/Rust gateway implementation (10x faster)
- Advanced ML-based prediction
- Distributed caching (multi-node)
- Grafana dashboards
- More approximation strategies
- Enterprise features (SSO, audit logs)
๐ฌ Support
- ๐ง Email: hello@latencyzero.ai
- ๐ฌ Discord: Join our community
- ๐ Docs: docs.latencyzero.ai
- ๐ Issues: GitHub Issues
๐ Try It Now!
# Install
pip install latencyzero
# Start gateway
python gateway/server.py
# Add decorator
@a3(tolerance=0.02)
def my_expensive_function():
...
# Enjoy 50-90% latency reduction! ๐
Built with โค๏ธ by the LatencyZero team
Serve answers before the question finishes.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file latencyzero-0.1.0.tar.gz.
File metadata
- Download URL: latencyzero-0.1.0.tar.gz
- Upload date:
- Size: 35.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
61327160a6b5f407ed8f9e30d001ab51c84c903f739df7ff26ae386a4438f9ea
|
|
| MD5 |
5981a66d3ba6e379d5aceae663659db8
|
|
| BLAKE2b-256 |
19598298e33564efd4c22dc24eb43491ae56437fde20d7bc95b538bd8d53c06f
|
File details
Details for the file latencyzero-0.1.0-py3-none-any.whl.
File metadata
- Download URL: latencyzero-0.1.0-py3-none-any.whl
- Upload date:
- Size: 38.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
41d64f5f38b7acd8dd2c772603d03f301ce88b8feb08d2325e84b330eeb6cb9f
|
|
| MD5 |
1961fa3f512cc6aeac59f04ecbb19e4d
|
|
| BLAKE2b-256 |
05976961543f42a9daee80148cbc2db40c6e4a830dd4d7d92d6c142f4f819355
|