From b4bf6d01c34149f5cb653b762f751db27582a39e Mon Sep 17 00:00:00 2001 From: Klaas van Schelven Date: Mon, 17 Feb 2025 13:31:03 +0100 Subject: [PATCH] Make import lazy for performance reasons ('cold start') --- events/ua_stuff.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/events/ua_stuff.py b/events/ua_stuff.py index 3ac4171..c008741 100644 --- a/events/ua_stuff.py +++ b/events/ua_stuff.py @@ -1,5 +1,4 @@ import logging -from user_agents import parse as ua_parse logger = logging.getLogger("bugsink.events.ua_stuff") @@ -19,6 +18,14 @@ def enrich_contexts_with_ua(parsed_data): # competitors to give OS/browser info the main stage (icons? yuck!). So we'll just parse it, put it "somewhere", and # look at it again "later". + # lazy import for performance, because of the many compiled regexes in the user_agents module this takes .2s (local + # laptop as well as on random GCP server). When this is a top-level import, this cost is incurred on the first + # request (via urls.py), which is a problem when many first requests happen simultaneously (typically: through + # the ingestion API) and these contend for CPU to do this import. ("cold start in a hot env"). Making this import + # lazy avoids the problem, because only the first UI request (typically less hot and more spaced out) will do the + # import. + from user_agents import parse as ua_parse + try: contexts = parsed_data.get("contexts", {})