Add persistent API quota tracking - #142
Open
Kanika0306 wants to merge 1 commit into
Open
Conversation
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.
Comments suppressed due to low confidence (1)
app/routes/api.py:75
- These endpoints re-read
X-API-Keyfromrequest.headersand include a reverse lookup fallback byuser_info['name']. Sinceverify_api_keyalready validated the header value, consider passing the validatedapi_keythrough (e.g., include it in the dependency return or store it onrequest.state) and dropping the name-based fallback. This reduces duplicated logic and avoids potentialStopIteration/misattribution if the fallback ever runs (e.g., in tests or future refactors).
api_key = request.headers.get("X-API-Key") if request else None
if not api_key:
api_key = next(
key for key, value in settings.API_KEYS.items()
if value['name'] == user_info['name']
)
quota = check_and_increment_quota(api_key, db)
Author
|
@copilot apply changes based on the comments in this thread |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.
Comments suppressed due to low confidence (3)
app/routes/api.py:116
- Same as above: quota enforcement re-derives
api_keyfrom the request / user name rather than reusing the already-validated key fromverify_api_key, which duplicates logic and can raiseStopIterationif the reverse lookup fails.
api_key = request.headers.get("X-API-Key") if request else None
if not api_key:
api_key = next(
key for key, value in settings.API_KEYS.items()
if value['name'] == user_info['name']
)
quota = check_and_increment_quota(api_key, db)
app/routes/api.py:154
- Same issue here: the endpoint reconstructs
api_key(including a reverse lookup by user name) instead of reusing the validated API key from the auth dependency. Returning/storing the API key during auth would remove this repeated block and avoidStopIterationedge cases.
api_key = request.headers.get("X-API-Key") if request else None
if not api_key:
api_key = next(
key for key, value in settings.API_KEYS.items()
if value['name'] == user_info['name']
)
quota = check_and_increment_quota(api_key, db)
app/routes/api.py:276
- Same issue here: quota enforcement depends on reconstructing
api_keyinstead of using the authenticated key fromverify_api_key. Refactoring the dependency to provide theapi_keywould remove this repeated code and avoid reverse-lookup edge cases.
api_key = request.headers.get("X-API-Key") if request else None
if not api_key:
api_key = next(
key for key, value in settings.API_KEYS.items()
if value['name'] == user_info['name']
)
quota = check_and_increment_quota(api_key, db)
Comment on lines
+69
to
+75
| api_key = request.headers.get("X-API-Key") if request else None | ||
| if not api_key: | ||
| api_key = next( | ||
| key for key, value in settings.API_KEYS.items() | ||
| if value['name'] == user_info['name'] | ||
| ) | ||
| quota = check_and_increment_quota(api_key, db) |
|
|
||
| from fastapi import HTTPException | ||
| from sqlalchemy.orm import Session | ||
| from sqlalchemy.exc import IntegrityError |
Comment on lines
+90
to
+93
| # A missing row here is a visibility/setup issue, not quota exhaustion. | ||
| if row is None: | ||
| db.commit() | ||
| return {"remaining": max_req, "total": max_req} |
Comment on lines
+109
to
+140
| try: | ||
| from sqlalchemy.pool import NullPool | ||
| engine = create_engine( | ||
| f"sqlite:///{db_path}", | ||
| connect_args={"check_same_thread": False, "timeout": 30}, | ||
| poolclass=NullPool, # Each thread gets its own connection | ||
| ) | ||
| Base.metadata.create_all(engine) | ||
| SessionLocal = sessionmaker(bind=engine) | ||
|
|
||
| def worker(): | ||
| db = SessionLocal() | ||
| try: | ||
| return check_and_increment_quota("key1", db) | ||
| finally: | ||
| db.close() | ||
|
|
||
| with ThreadPoolExecutor(max_workers=10) as executor: | ||
| results = list(executor.map(lambda _: worker(), range(10))) | ||
|
|
||
| assert len(results) == 10 | ||
|
|
||
| # Verify DB count matches exactly | ||
| db = SessionLocal() | ||
| row = db.query(APIQuota).filter(APIQuota.api_key == "key1").first() | ||
| db.close() | ||
| assert row.request_count == 10, f"Expected 10, got {row.request_count}" | ||
|
|
||
| engine.dispose() | ||
| finally: | ||
| if os.path.exists(db_path): | ||
| os.unlink(db_path) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR solves Issue #141 by replacing the previous in-memory daily quota tracking system with a persistent database-backed implementation. Quota usage is now stored and enforced through the database, ensuring request limits remain accurate across sessions, engine recreation, and concurrent access.
What Changed
APIQuotamodel to store per-API-key daily request countscheck_and_increment_quota()inapp/quota.pyfor centralized quota handlingWhy
The previous implementation relied on in-memory state, which was not durable across reconnects or restarts and was vulnerable to inconsistencies during concurrent access.
This also exposed an edge case where a temporarily missing quota row could be misinterpreted as quota exhaustion, causing valid requests to receive false:
429 Daily request quota exceededresponses.
Result
Quota tracking is now:
Closes #141
Testing
Executed: