feat: add optional garbage collection after requests (#35061)

Co-authored-by: Claude <noreply@anthropic.com>
diff --git a/superset/config.py b/superset/config.py
index 856b604..662e795 100644
--- a/superset/config.py
+++ b/superset/config.py
@@ -626,6 +626,8 @@
     "DATE_RANGE_TIMESHIFTS_ENABLED": False,
     # Enable Matrixify feature for matrix-style chart layouts
     "MATRIXIFY": False,
+    # Force garbage collection after every request
+    "FORCE_GARBAGE_COLLECTION_AFTER_EVERY_REQUEST": False,
 }
 
 # ------------------------------
diff --git a/superset/initialization/__init__.py b/superset/initialization/__init__.py
index 82296e0..133456f 100644
--- a/superset/initialization/__init__.py
+++ b/superset/initialization/__init__.py
@@ -638,6 +638,17 @@
                     response.headers[k] = v
             return response
 
+        @self.superset_app.after_request
+        def cleanup_analytics_memory(response: Response) -> Response:
+            """Force garbage collection after each request if feature flag enabled"""
+            if feature_flag_manager.is_feature_enabled(
+                "FORCE_GARBAGE_COLLECTION_AFTER_EVERY_REQUEST"
+            ):
+                import gc
+
+                gc.collect()
+            return response
+
         @self.superset_app.context_processor
         def get_common_bootstrap_data() -> dict[str, Any]:
             # Import here to avoid circular imports