Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@
## 2025-07-14 - [Aggregation for Activity Feeds]
**Learning:** Replacing loop-based lookups (N+1 queries) with single aggregation pipelines in `get_recent_activity` reduces database roundtrips by over 90% (from 42 queries to 2). Using `$unwind` without `preserveNullAndEmptyArrays` effectively replicates `if tool and worker:` filtering logic in the database layer.
**Action:** Apply similar aggregation patterns to other feed-like features (e.g., `manual_lending` in `app/routes/admin/system.py`).
## 2026-02-18 - [N+1 Query in Lending Feed]
**Learning:** Found a core N+1 bottleneck in LendingService.get_active_lendings where each active lending triggered separate tool and worker lookups.
**Action:** Replaced loop-based enrichment with a single MongoDB aggregation pipeline using $lookup. This reduces database roundtrips from 1+2N to 1, providing a major speed boost for high-volume environments.
60 changes: 40 additions & 20 deletions app/services/lending_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,27 +341,47 @@ def _process_consumable_lending(item_barcode: str, worker_barcode: str, action:

@staticmethod
def get_active_lendings() -> list:
"""Holt alle aktiven Ausleihen"""
"""
Holt alle aktiven Ausleihen
OPTIMIERT: Verwendet Aggregation-Pipeline zur Vermeidung von N+1 Queries
"""
try:
active_lendings = mongodb.find('lendings', {'returned_at': None})

# Erweitere mit Tool- und Worker-Informationen
enriched_lendings = []
for lending in active_lendings:
tool = mongodb.find_one('tools', {'barcode': lending['tool_barcode']})
worker = mongodb.find_one('workers', {'barcode': lending['worker_barcode']})

if tool and worker:
enriched_lendings.append({
**lending,
'tool_name': tool['name'],
'worker_name': f"{worker['firstname']} {worker['lastname']}",
'lent_at': lending['lent_at']
})

# Sortiere nach Datum (neueste zuerst)
enriched_lendings.sort(key=lambda x: x.get('lent_at', datetime.min), reverse=True)
return enriched_lendings
pipeline = [
{'$match': {'returned_at': None}},
{
'$lookup': {
'from': 'tools',
'localField': 'tool_barcode',
'foreignField': 'barcode',
'as': 'tool'
}
},
{'$unwind': '$tool'},
{
'$lookup': {
'from': 'workers',
'localField': 'worker_barcode',
'foreignField': 'barcode',
'as': 'worker'
}
},
{'$unwind': '$worker'},
{
'$addFields': {
'tool_name': '$tool.name',
'worker_name': {'$concat': ['$worker.firstname', ' ', '$worker.lastname']}
}
},
{
'$project': {
'tool': 0,
'worker': 0
}
},
{'$sort': {'lent_at': -1}}
]

return mongodb.aggregate('lendings', pipeline)

except Exception as e:
logger.error(f"Fehler beim Laden aktiver Ausleihen: [Interner Fehler]")
Expand Down