Best Practices

Learn best practices for building robust, efficient, and secure applications with Sematryx.

Security

API Key Management

Never commit API keys to version control. Always use environment variables or secure secret management:

Secure API key handling
# ✅ Good: Use environment variables
import os
from sematryx import SematryxClient

client = SematryxClient(api_key=os.getenv('SEMATRYX_API_KEY'))

# ❌ Bad: Hardcoded API key
client = SematryxClient(api_key='sk_live_1234567890')

Security Checklist

  • ✅ Store API keys in environment variables
  • ✅ Use different keys for development and production
  • ✅ Rotate API keys regularly
  • ✅ Never log API keys or include them in error messages
  • ✅ Use HTTPS for all API requests
  • ✅ Verify webhook signatures

Error Handling

Always implement comprehensive error handling for production applications:

Proper error handling
# ✅ Good: Comprehensive error handling
try:
    result = client.optimize(objective, bounds)
except RateLimitError as e:
    # Wait for rate limit reset
    wait_until(e.reset_time)
    result = client.optimize(objective, bounds)
except ValidationError as e:
    # Fix validation issues
    logger.error(f"Validation error: {e.message}")
    raise
except SematryxError as e:
    # Log and handle other errors
    logger.error(f"Error: {e.message}")
    raise

# ❌ Bad: Silent error handling
try:
    result = client.optimize(objective, bounds)
except:
    pass  # Errors are ignored

Error Handling Principles

  • Handle specific error types appropriately
  • Implement retry logic for transient errors
  • Log errors with context for debugging
  • Provide meaningful error messages to users
  • Never silently ignore errors

Performance Optimization

Async Operations

Use async/await for concurrent operations to improve performance:

Async patterns
# ✅ Good: Use async for concurrent operations
import asyncio
from sematryx import AsyncSematryx

async def optimize_multiple(objectives):
    client = AsyncSematryx(api_key=api_key)
    results = await asyncio.gather(*[
        client.optimize(obj, bounds) for obj in objectives
    ])
    return results

# ❌ Bad: Sequential blocking calls
results = []
for objective in objectives:
    result = client.optimize(objective, bounds)
    results.append(result)

Caching

Cache results when appropriate to reduce API calls:

Result caching
# ✅ Good: Cache results when appropriate
from functools import lru_cache

@lru_cache(maxsize=100)
def cached_optimization(problem_hash):
    return client.optimize(objective, bounds)

# ❌ Bad: Always make new API calls
def always_fetch():
    return client.optimize(objective, bounds)  # No caching

Webhooks vs Polling

Use webhooks instead of polling for real-time updates:

Webhooks vs polling
# ✅ Good: Use webhooks for real-time updates
webhook = client.webhooks.create(
    url='https://your-app.com/webhooks/aeao',
    events=['automation.completed']
)

# ❌ Bad: Polling for status updates
while True:
    status = client.get_status(id)
    if status == 'completed':
        break
    time.sleep(5)  # Wasteful polling

Rate Limit Management

Rate Limit Best Practices

  • Monitor rate limit headers on every request
  • Implement exponential backoff for retries
  • Batch requests when possible
  • Use webhooks to reduce polling overhead
  • Cache responses to minimize API calls
  • Plan request patterns to stay within limits

Code Organization

Modular Design

  • Separate API client initialization from business logic
  • Create reusable functions for common operations
  • Use configuration files for environment-specific settings
  • Implement proper logging and monitoring

Testing

  • Write unit tests for API integration code
  • Use mock responses for testing
  • Test error handling scenarios
  • Test rate limit handling

Monitoring and Observability

What to Monitor

  • API Response Times: Track latency and identify slow endpoints
  • Error Rates: Monitor error frequency and types
  • Rate Limit Usage: Track rate limit consumption
  • Request Patterns: Identify optimization opportunities
  • Cost Tracking: Monitor API usage costs

Production Checklist

Before Going to Production

  • ✅ API keys stored securely (environment variables, secrets manager)
  • ✅ Error handling implemented for all API calls
  • ✅ Rate limit handling with retry logic
  • ✅ Logging and monitoring configured
  • ✅ Webhook signature verification implemented
  • ✅ Timeout values configured appropriately
  • ✅ Tests written and passing
  • ✅ Documentation updated