Skip to main content

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

  1. First Call (Exact)

    • Query arrives at gateway
    • No approximation available
    • Execute exact computation
    • Store result for future use
    • Return to caller (~2000ms)
  2. 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
  3. 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

๐ŸŽ‰ 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

latencyzero-0.1.0.tar.gz (35.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

latencyzero-0.1.0-py3-none-any.whl (38.2 kB view details)

Uploaded Python 3

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

Hashes for latencyzero-0.1.0.tar.gz
Algorithm Hash digest
SHA256 61327160a6b5f407ed8f9e30d001ab51c84c903f739df7ff26ae386a4438f9ea
MD5 5981a66d3ba6e379d5aceae663659db8
BLAKE2b-256 19598298e33564efd4c22dc24eb43491ae56437fde20d7bc95b538bd8d53c06f

See more details on using hashes here.

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

Hashes for latencyzero-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 41d64f5f38b7acd8dd2c772603d03f301ce88b8feb08d2325e84b330eeb6cb9f
MD5 1961fa3f512cc6aeac59f04ecbb19e4d
BLAKE2b-256 05976961543f42a9daee80148cbc2db40c6e4a830dd4d7d92d6c142f4f819355

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page