Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Improve document read/write performance (#76018)

Nathan Voxland540817adfe71
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 0eb85257b0e..59f6dec1c0d 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -143,6 +143,7 @@
metabase.activity-feed.init}
:uses #{api
app-db
+ batch-processing
collections
config
events
diff --git a/src/metabase/activity_feed/models/recent_views.clj b/src/metabase/activity_feed/models/recent_views.clj
index ae3589ee752..318be6485db 100644
--- a/src/metabase/activity_feed/models/recent_views.clj
+++ b/src/metabase/activity_feed/models/recent_views.clj
@@ -29,6 +29,7 @@
[malli.core :as mc]
[malli.error :as me]
[medley.core :as m]
+ [metabase.batch-processing.core :as grouper]
[metabase.collections.models.collection :as collection]
[metabase.collections.models.collection.root :as root]
[metabase.config.core :as config]
@@ -144,6 +145,42 @@
(duplicate-model-ids user-id context)
(overflowing-model-buckets user-id context)))
+(defn- update-users-recent-views!*
+ "Batch handler for [[update-users-recent-views!]]: inserts the given views and then prunes overflow and
+ duplicates once per affected (user, context) pair."
+ [views]
+ (when (seq views)
+ (try
+ (t2/with-transaction [_conn]
+ (t2/insert! :model/RecentViews
+ (for [{:keys [user-id model model-id context timestamp]} views]
+ {:user_id user-id
+ :model (u/lower-case-en (name model))
+ :model_id model-id
+ :context (name context)
+ :timestamp timestamp}))
+ ;; The prune queries are per (user, context), not per view, so collapse the batch down to its distinct
+ ;; pairs first: N views by one user become one set of prune queries instead of N.
+ (let [prune-ids (into #{}
+ (comp (map (juxt :user-id :context))
+ (distinct)
+ (mapcat (fn [[user-id context]] (ids-to-prune user-id context))))
+ views)]
+ (when (seq prune-ids)
+ (t2/delete! :model/RecentViews :id [:in prune-ids]))))
+ (catch Exception e
+ (log/error e "Failed to update users recent views")))))
+
+(def ^:private recent-views-interval-seconds 20)
+
+(def ^:private recent-views-queue-capacity 500)
+
+(defonce ^:private recent-views-queue
+ (delay (grouper/start!
+ #'update-users-recent-views!*
+ :capacity recent-views-queue-capacity
+ :interval (* recent-views-interval-seconds 1000))))
+
(mu/defn update-users-recent-views!
"Updates the RecentViews table for a given user with a new view, and prunes old views."
[user-id :- [:maybe ms/PositiveInt]
@@ -151,14 +188,11 @@
model-id :- ms/PositiveInt
context :- [:enum :view :selection]]
(when user-id
- (t2/with-transaction [_conn]
- (t2/insert! :model/RecentViews {:user_id user-id
- :model (u/lower-case-en (name model))
- :model_id model-id
- :context (name context)})
- (let [prune-ids (ids-to-prune user-id context)]
- (when (seq prune-ids)
- (t2/delete! :model/RecentViews :id [:in prune-ids]))))))
+ (grouper/submit! @recent-views-queue {:user-id user-id
+ :model model
+ :model-id model-id
+ :context context
+ :timestamp (t/offset-date-time)})))
(defn most-recently-viewed-dashboard-id
"Returns ID of the most recently viewed dashboard for a given user within the last 24 hours, or `nil`."
diff --git a/src/metabase/documents/api/document.clj b/src/metabase/documents/api/document.clj
index ac674821730..8fcfedb2edd 100644
--- a/src/metabase/documents/api/document.clj
+++ b/src/metabase/documents/api/document.clj
@@ -173,13 +173,19 @@
{}
to-clone))))
+(defn- hydrate-document
+ "Fetch a document by id along with the derived fields the API returns. Does *not* check permissions or
+ publish a read event, so it is safe to use on write paths (PUT/POST) where recording a view would be
+ both semantically wrong and an extra, avoidable round-trip."
+ [id]
+ (t2/hydrate (t2/select-one :model/Document :id id)
+ :creator :can_write :can_delete :can_restore :is_remote_synced))
+
(defn get-document
- "Get document by id checking if the current user has permission to access and if the document exists.
+ "Get document by id, checking that it exists and the current user can read it, and recording a view.
Pass `:log-view? false` to skip publishing the `:event/document-read` view event."
[id & {:keys [log-view?] :or {log-view? true}}]
- (u/prog1 (api/check-404
- (api/read-check
- (t2/hydrate (t2/select-one :model/Document :id id) :creator :can_write :can_delete :can_restore :is_remote_synced)))
+ (u/prog1 (api/check-404 (api/read-check (hydrate-document id)))
(when log-view?
(events/publish-event! :event/document-read
{:object-id id
@@ -293,7 +299,8 @@
(api.macros/defendpoint :get "/:document-id"
"Returns an existing Document by ID."
[{:keys [document-id]} :- [:map [:document-id ms/PositiveInt]]]
- (api/read-check (get-document document-id)))
+ ;; `get-document` already does the 404 + read-check internally;
+ (get-document document-id))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
@@ -305,7 +312,10 @@
[:document-id ms/PositiveInt]]
_query-params
{:keys [name document collection_id collection_position cards] :as body} :- DocumentUpdateOptions]
- (let [existing-document (api/check-404 (get-document document-id))]
+ ;; Use a lightweight fetch for the guard: we only need the raw row for the archived/permission/collection-move
+ ;; checks below. Calling `get-document` here would hydrate display fields we don't use and record a *view* of
+ ;; the document on every save.
+ (let [existing-document (api/check-404 (t2/select-one :model/Document :id document-id))]
(when-not (contains? body :archived)
(api/check-not-archived existing-document))
(api/write-check existing-document)
@@ -343,7 +353,9 @@
(when (seq pairings)
(card/carry-pairings-for-document! document-id pairings)))
(collections/check-for-remote-sync-update existing-document))
- (let [updated-document (get-document document-id)]
+ ;; `hydrate-document` (not `get-document`): the write already passed `write-check`, and a save is not a view,
+ ;; so we neither re-check read perms nor publish a read event for the returned instance.
+ (let [updated-document (hydrate-document document-id)]
;; Publish appropriate events
(if (:archived document-updates)
(events/publish-event! :event/document-delete
diff --git a/test/metabase/activity_feed/models/recent_views_test.clj b/test/metabase/activity_feed/models/recent_views_test.clj
index a8d96ea2391..629bc96d60a 100644
--- a/test/metabase/activity_feed/models/recent_views_test.clj
+++ b/test/metabase/activity_feed/models/recent_views_test.clj
@@ -1,4 +1,4 @@
-(ns metabase.activity-feed.models.recent-views-test
+(ns ^:synchronized metabase.activity-feed.models.recent-views-test
(:require
[clojure.string :as str]
[clojure.test :refer :all]
@@ -20,7 +20,8 @@
(use-fixtures
:each (fn [f]
(clear-test-user-recent-views)
- (f)))
+ (mt/with-temporary-setting-values [synchronous-batch-updates true]
+ (f))))
(defn fixup [list-item]
(-> list-item
diff --git a/test/metabase/documents/api/document_test.clj b/test/metabase/documents/api/document_test.clj
index 15452a5cdac..7150ff4aa97 100644
--- a/test/metabase/documents/api/document_test.clj
+++ b/test/metabase/documents/api/document_test.clj
@@ -122,6 +122,38 @@
(mt/user-http-request :crowberto
:get 404 "document/99999")))))
+(defn- recent-view
+ "The RecentViews row, if any, for `user-id` viewing document `document-id`. Document reads record a recent
+ view (asynchronously via grouper, so these tests force synchronous batching), giving us a reliable signal
+ of whether a request counted as a view."
+ [user-id document-id]
+ (t2/select-one :model/RecentViews
+ :user_id user-id
+ :model "document"
+ :model_id document-id))
+
+(deftest get-document-records-view-test
+ (testing "GET /api/document/:id records the read as a recent view"
+ (mt/with-temporary-setting-values [synchronous-batch-updates true]
+ (mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")}]
+ (is (nil? (recent-view (mt/user->id :crowberto) document-id))
+ "no recent view should exist before reading")
+ (mt/user-http-request :crowberto :get 200 (format "document/%s" document-id))
+ (is (some? (recent-view (mt/user->id :crowberto) document-id))
+ "reading a document should record a recent view")))))
+
+(deftest put-document-does-not-record-view-test
+ (testing "PUT /api/document/:id should not record a view (saving is not a read)"
+ (mt/with-temporary-setting-values [synchronous-batch-updates true]
+ (mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")}]
+ (mt/user-http-request :crowberto
+ :put 200 (format "document/%s" document-id)
+ {:name "Updated" :document (documents.test-util/text->prose-mirror-ast "Updated Doc")})
+ (is (nil? (recent-view (mt/user->id :crowberto) document-id))
+ "saving a document should not record a recent view")))))
+
(deftest get-documents-test
(testing "GET /api/document"
(mt/with-temp [:model/Document _ {:name "Document 1"
diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.clj
index 6955cd45395..82c338cad0b 100644
--- a/test/metabase/queries_rest/api/card_test.clj
+++ b/test/metabase/queries_rest/api/card_test.clj
@@ -925,24 +925,25 @@
(deftest create-a-card-with-result-metadata-updates-recents-test
(testing "POST /api/card adds user-created questions to recents (UXW-3171)"
- (mt/with-full-data-perms-for-all-users!
- (mt/with-model-cleanup [:model/Card]
- (t2/delete! :model/RecentViews :user_id (mt/user->id :rasta))
- (let [card (assoc (card-with-name-and-query) :result_metadata [])
- card-id (:id (mt/user-http-request :rasta :post 200 "card" card))]
- (is (= {:user_id (mt/user->id :rasta)
- :model "card"
- :model_id card-id}
- (t2/select-one [:model/RecentViews :user_id :model :model_id]
- :user_id (mt/user->id :rasta)
- :model_id card-id
- :model "card"))))
- (testing "Cards saved without result metadata are not treated as viewed"
- (let [card-id (:id (mt/user-http-request :rasta :post 200 "card" (card-with-name-and-query)))]
- (is (nil? (t2/select-one :model/RecentViews
- :user_id (mt/user->id :rasta)
- :model_id card-id
- :model "card")))))))))
+ (mt/with-temporary-setting-values [synchronous-batch-updates true]
+ (mt/with-full-data-perms-for-all-users!
+ (mt/with-model-cleanup [:model/Card]
+ (t2/delete! :model/RecentViews :user_id (mt/user->id :rasta))
+ (let [card (assoc (card-with-name-and-query) :result_metadata [])
+ card-id (:id (mt/user-http-request :rasta :post 200 "card" card))]
+ (is (= {:user_id (mt/user->id :rasta)
+ :model "card"
+ :model_id card-id}
+ (t2/select-one [:model/RecentViews :user_id :model :model_id]
+ :user_id (mt/user->id :rasta)
+ :model_id card-id
+ :model "card"))))
+ (testing "Cards saved without result metadata are not treated as viewed"
+ (let [card-id (:id (mt/user-http-request :rasta :post 200 "card" (card-with-name-and-query)))]
+ (is (nil? (t2/select-one :model/RecentViews
+ :user_id (mt/user->id :rasta)
+ :model_id card-id
+ :model "card"))))))))))
(deftest ^:parallel create-card-validation-test
(testing "POST /api/card"