Skip to content

Instantly share code, notes, and snippets.

@DKbyo
Created March 7, 2024 03:17
Show Gist options
  • Select an option

  • Save DKbyo/e7f77e919ddeafb188025b3eb2831681 to your computer and use it in GitHub Desktop.

Select an option

Save DKbyo/e7f77e919ddeafb188025b3eb2831681 to your computer and use it in GitHub Desktop.
AsyncIO + FastAPI + Uvicorn + Firestore Example
FROM python:3.9-alpine
COPY requirements.txt /tmp/requirements.txt
RUN pip install --no-cache-dir -r /tmp/requirements.txt
WORKDIR /app
COPY main.py /app
CMD uvicorn --host 0.0.0.0 --port $PORT --workers $WORKERS main:app
from firebase_admin import firestore_async, initialize_app
import socket
from fastapi import FastAPI
import traceback
import logging
logger = logging.getLogger(__name__)
app = FastAPI()
initialize_app()
counter = 0
@app.get("/")
async def read_root():
db = firestore_async.client()
logger.info("global counter")
global counter
logger.info("db.collection('test')")
col = db.collection("test")
logger.info("col.document('testDoc')")
doc = col.document("testDoc")
logger.info("doc.get()")
get = await doc.get()
logger.info("get.to_dict()")
data_dict = get.to_dict()
logger.info("counter += 1")
counter += 1
logger.info("counter", counter, "data", data_dict)
return f"counter {counter} data {data_dict}"
uvicorn[standard]
fastapi[all]
firebase-admin

Where WORKERS might be the expected concurrency as described on https://www.uvicorn.org/#usage and credentials.json is the JSON key credentials for a Service Account with Firebase Admin Role

❯ docker run -d  -p 8080:8080 --volume <PATH_TO_CREDENTIALS>/credentials.json:/creds/credentials.json  -e PORT=8080 -e WORKERS=8 -e GOOGLE_APPLICATION_CREDENTIALS=/creds/credentials.json <CONTAINER_ID>
❯ hey -n 1000 -c 1000 http://localhost:8080

Summary:
  Total:        6.7427 secs
  Slowest:      6.7380 secs
  Fastest:      0.8480 secs
  Average:      2.7243 secs
  Requests/sec: 148.3079
  
  Total data:   54136 bytes
  Size/request: 54 bytes

Response time histogram:
  0.848 [1]     |
  1.437 [16]    |■
  2.026 [734]   |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
  2.615 [47]    |■■■
  3.204 [0]     |
  3.793 [0]     |
  4.382 [0]     |
  4.971 [0]     |
  5.560 [9]     |
  6.149 [122]   |■■■■■■■
  6.738 [71]    |■■■■


Latency distribution:
  10% in 1.7767 secs
  25% in 1.8955 secs
  50% in 1.9508 secs
  75% in 2.0256 secs
  90% in 5.9937 secs
  95% in 6.2856 secs
  99% in 6.5654 secs

Details (average, fastest, slowest):
  DNS+dialup:   0.1213 secs, 0.8480 secs, 6.7380 secs
  DNS-lookup:   0.0917 secs, 0.0000 secs, 0.1767 secs
  req write:    0.0033 secs, 0.0000 secs, 0.1484 secs
  resp wait:    2.5850 secs, 0.7269 secs, 6.5992 secs
  resp read:    0.0001 secs, 0.0000 secs, 0.0004 secs

Status code distribution:
  [200] 1000 responses
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment