Skip to main content

Seamlessly track SQLAlchemy performance in FastAPI with plug-and-play monitoring middleware 🔍

Project description

FastAPI SQLAlchemy Monitor

PyPI version License: MIT Test Python Versions

A middleware for FastAPI that monitors SQLAlchemy database queries, providing insights into database usage patterns and helping catch potential performance issues.

Features

  • 📊 Track total database query invocations and execution times
  • 🔍 Detailed per-query statistics
  • ⚡ Async support
  • 🎯 Configurable actions for monitoring and alerting
  • 🛡️ Built-in protection against N+1 query problems

Installation

pip install fastapi-sqlalchemy-monitor

Quick Start

from fastapi import FastAPI
from sqlalchemy import create_engine

from fastapi_sqlalchemy_monitor import SQLAlchemyMonitor
from fastapi_sqlalchemy_monitor.action import WarnMaxTotalInvocation, PrintStatistics

# Create async engine
engine = create_engine("sqlite:///./test.db")

app = FastAPI()

# Add the middleware with actions
app.add_middleware(
    SQLAlchemyMonitor,
    engine=engine,
    actions=[
        WarnMaxTotalInvocation(max_invocations=10),  # Warn if too many queries
        PrintStatistics()  # Print statistics after each request
    ]
)

Actions

The middleware supports different types of actions that can be triggered based on query statistics.

Built-in Actions

  • WarnMaxTotalInvocation: Log a warning when query count exceeds threshold
  • ErrorMaxTotalInvocation: Log an error when query count exceeds threshold
  • RaiseMaxTotalInvocation: Raise an exception when query count exceeds threshold
  • LogStatistics: Log query statistics
  • PrintStatistics: Print query statistics

Custom Actions

The middleware provides two interfaces for implementing custom actions:

  • Action: Simple interface that executes after every request
  • ConditionalAction: Advanced interface that executes only when specific conditions are met

Basic Custom Action

Here's an example of a custom action that records Prometheus metrics:

from prometheus_client import Counter

from fastapi_sqlalchemy_monitor import AlchemyStatistics
from fastapi_sqlalchemy_monitor.action import Action

class PrometheusAction(Action):
    def __init__(self):
        self.query_counter = Counter(
            'sql_queries_total', 
            'Total number of SQL queries executed'
        )
        
    def handle(self, statistics: AlchemyStatistics):
        self.query_counter.inc(statistics.total_invocations)

Conditional Action Example

Here's an example of a conditional action that monitors for slow queries:

import logging

from fastapi_sqlalchemy_monitor import AlchemyStatistics
from fastapi_sqlalchemy_monitor.action import ConditionalAction

class SlowQueryMonitor(ConditionalAction):
    def __init__(self, threshold_ms: float):
        self.threshold_ms = threshold_ms

    def _condition(self, statistics: AlchemyStatistics) -> bool:
        # Check if any query exceeds the time threshold
        return any(
            query.total_invocation_time_ms > self.threshold_ms 
            for query in statistics.query_stats.values()
        )

    def _handle(self, statistics: AlchemyStatistics):
        # Log details of slow queries
        for query_stat in statistics.query_stats.values():
            if query_stat.total_invocation_time_ms > self.threshold_ms:
                logging.warning(
                    f"Slow query detected ({query_stat.total_invocation_time_ms:.2f}ms): "
                    f"{query_stat.query}"
                )

Using Custom Actions

Here's how to use custom actions:

app.add_middleware(
    SQLAlchemyMonitor,
    engine=engine,
    actions=[
        PrometheusAction(),
        SlowQueryMonitor(threshold_ms=100)
    ]
)

Available Statistics

When implementing custom actions, you have access to these statistics properties:

  • statistics.total_invocations: Total number of queries executed
  • statistics.total_invocation_time_ms: Total execution time in milliseconds
  • statistics.query_stats: Dictionary of per-query statistics

Each QueryStatistic in query_stats contains:

  • query: The SQL query string
  • total_invocations: Number of times this query was executed
  • total_invocation_time_ms: Total execution time for this query
  • invocation_times_ms: List of individual execution times

Best Practices

  1. Keep actions focused on a single responsibility
  2. Use appropriate log levels for different severity conditions
  3. Consider performance impact of complex evaluations
  4. Use type hints for better code maintenance

Example with Async SQLAlchemy

from fastapi import FastAPI
from sqlalchemy.ext.asyncio import create_async_engine

from fastapi_sqlalchemy_monitor import SQLAlchemyMonitor
from fastapi_sqlalchemy_monitor.action import PrintStatistics

# Create async engine
engine = create_async_engine("sqlite+aiosqlite:///./test.db")

app = FastAPI()

# Add middleware
app.add_middleware(
    SQLAlchemyMonitor,
    engine=engine,
    actions=[PrintStatistics()]
)

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License.

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

fastapi_sqlalchemy_monitor-1.0.0.tar.gz (74.9 kB view details)

Uploaded Source

Built Distribution

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

fastapi_sqlalchemy_monitor-1.0.0-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_sqlalchemy_monitor-1.0.0.tar.gz.

File metadata

File hashes

Hashes for fastapi_sqlalchemy_monitor-1.0.0.tar.gz
Algorithm Hash digest
SHA256 1c752ae089b5dd4b57c504ffe1c3790179a7232d760ca82ca73700776581ad50
MD5 468a3ac0abd5d9458b07d90a66ef937e
BLAKE2b-256 13330a034ffa148e1a6653c685e28d4fce9be441020fba7b19cc1e3c223243e3

See more details on using hashes here.

File details

Details for the file fastapi_sqlalchemy_monitor-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_sqlalchemy_monitor-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 897586c56ab9f6cdeca174f0743e7491531b96302f835fd7aa6da4412602f6e0
MD5 f436bbb0dd478c2cf04386b7c0caaea5
BLAKE2b-256 42e46ae5748db88d5b5ed93e5228e55c8fa278f4e09ca38641c75658f419bb89

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