perf(user): fetch latest usage timestamp with an index-backed lateral probe

Root cause: GetLatestUsedAtByUserIDs aggregated every historical usage_logs
row for the requested users (MAX(created_at) ... GROUP BY user_id). The
existing idx_usage_logs_user_created(user_id, created_at) index could not be
used to early-stop, so the admin user list paid O(history) per page and took
9-10s on million-row tables.

Change: probe only the newest row per requested user with
unnest($1::bigint[]) CROSS JOIN LATERAL (SELECT created_at FROM usage_logs
WHERE user_id = u.user_id ORDER BY created_at DESC LIMIT 1). Each inner
subquery is a single backward index scan on idx_usage_logs_user_created,
making the lookup O(page size * log n). The inner join preserves the previous
semantics: users without usage rows are absent from the returned map, and
timestamps are still normalized to UTC. GetLatestUsedAtByUserID keeps reusing
the batch function.

Tests: new sqlmock unit tests assert the lateral/ORDER BY ... LIMIT 1 query
shape, per-user latest result, missing-user omission, UTC normalization, empty
input short-circuit, no-rows, singleton reuse and error propagation. The
integration suite extends GetLatestUsedAtByUserIDs coverage with out-of-order
inserts across multiple users, a user without usage, and empty input.
This commit is contained in:
debug-zhang committed 2026-12-02 10:09:39 +08:00
1 parent f53641e53c
commit d762d5fa8a
3 files changed
+181 -4

No files matched your search

+16 -4
View File
@@ -732,11 +732,23 @@ func (r *userRepository) GetLatestUsedAtByUserIDs(ctx context.Context, userIDs [
return nil, fmt.Errorf("sql executor is not configured")
}
// Resolve each user's latest usage timestamp with an index-backed LATERAL
// probe instead of aggregating every historical usage_logs row. With the
// idx_usage_logs_user_created(user_id, created_at) index, the inner
// ORDER BY created_at DESC LIMIT 1 is a single backward index scan per user,
// so the cost is O(page size * log n) rather than O(history size).
// The inner join keeps the previous semantics: users without usage rows are
// absent from the result map.
const query = `
SELECT user_id, MAX(created_at) AS last_used_at
FROM usage_logs
WHERE user_id = ANY($1)
GROUP BY user_id
SELECT u.user_id, latest.created_at
FROM unnest($1::bigint[]) AS u(user_id)
CROSS JOIN LATERAL (
SELECT created_at
FROM usage_logs
WHERE user_id = u.user_id
ORDER BY created_at DESC
LIMIT 1
) AS latest
`
rows, err := r.sql.QueryContext(ctx, query, pq.Array(userIDs))
@@ -0,0 +1,120 @@
package repository
import (
"context"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/lib/pq"
"github.com/stretchr/testify/require"
)
// The previous implementation aggregated every historical usage_logs row per
// user with MAX(created_at) ... GROUP BY user_id, so its cost grew with the
// whole history. The replacement must probe only the newest row per user so
// that idx_usage_logs_user_created(user_id, created_at) can serve each lookup
// as a single backward index scan.
const latestUsedAtLateralQueryPattern = `(?s)SELECT u\.user_id, latest\.created_at\s+` +
`FROM unnest\(\$1::bigint\[\]\) AS u\(user_id\)\s+` +
`CROSS JOIN LATERAL \(\s+` +
`SELECT created_at\s+` +
`FROM usage_logs\s+` +
`WHERE user_id = u\.user_id\s+` +
`ORDER BY created_at DESC\s+` +
`LIMIT 1\s+` +
`\) AS latest`
func TestUserRepositoryGetLatestUsedAtByUserIDsUsesLateralProbe(t *testing.T) {
db, mock := newSQLMock(t)
repo := newUserRepositoryWithSQL(nil, db)
newestFor7 := time.Date(2026, 5, 4, 3, 2, 1, 0, time.FixedZone("UTC+8", 8*60*60))
newestFor8 := time.Date(2026, 5, 3, 1, 0, 0, 0, time.UTC)
// User 9 has no usage rows, so it is absent from the result set.
mock.ExpectQuery(latestUsedAtLateralQueryPattern).
WithArgs(pq.Array([]int64{7, 8, 9})).
WillReturnRows(sqlmock.NewRows([]string{"user_id", "created_at"}).
AddRow(int64(7), newestFor7).
AddRow(int64(8), newestFor8))
got, err := repo.GetLatestUsedAtByUserIDs(context.Background(), []int64{7, 8, 9})
require.NoError(t, err)
require.Len(t, got, 2)
require.NotContains(t, got, int64(9))
require.NotNil(t, got[7])
require.NotNil(t, got[8])
require.True(t, got[7].Equal(newestFor7))
require.True(t, got[8].Equal(newestFor8))
require.Equal(t, time.UTC, got[7].Location(), "timestamps must be normalized to UTC")
require.Equal(t, time.UTC, got[8].Location())
require.NoError(t, mock.ExpectationsWereMet())
}
func TestUserRepositoryGetLatestUsedAtByUserIDsEmptyInputSkipsQuery(t *testing.T) {
db, mock := newSQLMock(t)
repo := newUserRepositoryWithSQL(nil, db)
for _, ids := range [][]int64{nil, {}} {
got, err := repo.GetLatestUsedAtByUserIDs(context.Background(), ids)
require.NoError(t, err)
require.NotNil(t, got)
require.Empty(t, got)
}
// No query is expected or allowed for an empty ID list.
require.NoError(t, mock.ExpectationsWereMet())
}
func TestUserRepositoryGetLatestUsedAtByUserIDsNoUsageRows(t *testing.T) {
db, mock := newSQLMock(t)
repo := newUserRepositoryWithSQL(nil, db)
mock.ExpectQuery(latestUsedAtLateralQueryPattern).
WithArgs(pq.Array([]int64{42})).
WillReturnRows(sqlmock.NewRows([]string{"user_id", "created_at"}))
got, err := repo.GetLatestUsedAtByUserIDs(context.Background(), []int64{42})
require.NoError(t, err)
require.NotNil(t, got)
require.Empty(t, got)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestUserRepositoryGetLatestUsedAtByUserIDReusesBatchQuery(t *testing.T) {
db, mock := newSQLMock(t)
repo := newUserRepositoryWithSQL(nil, db)
newest := time.Date(2026, 5, 5, 4, 3, 2, 0, time.UTC)
mock.ExpectQuery(latestUsedAtLateralQueryPattern).
WithArgs(pq.Array([]int64{7})).
WillReturnRows(sqlmock.NewRows([]string{"user_id", "created_at"}).AddRow(int64(7), newest))
got, err := repo.GetLatestUsedAtByUserID(context.Background(), 7)
require.NoError(t, err)
require.NotNil(t, got)
require.True(t, got.Equal(newest))
mock.ExpectQuery(latestUsedAtLateralQueryPattern).
WithArgs(pq.Array([]int64{8})).
WillReturnRows(sqlmock.NewRows([]string{"user_id", "created_at"}))
missing, err := repo.GetLatestUsedAtByUserID(context.Background(), 8)
require.NoError(t, err)
require.Nil(t, missing)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestUserRepositoryGetLatestUsedAtByUserIDsPropagatesQueryError(t *testing.T) {
db, mock := newSQLMock(t)
repo := newUserRepositoryWithSQL(nil, db)
mock.ExpectQuery(latestUsedAtLateralQueryPattern).
WithArgs(pq.Array([]int64{7})).
WillReturnError(context.DeadlineExceeded)
got, err := repo.GetLatestUsedAtByUserIDs(context.Background(), []int64{7})
require.ErrorIs(t, err, context.DeadlineExceeded)
require.Nil(t, got)
require.NoError(t, mock.ExpectationsWereMet())
}
@@ -133,6 +133,51 @@ func (s *UserRepoSuite) TestGetLatestUsedAtByUserIDs_UsesUsageLogs() {
s.Require().True(got[userWithUsage.ID].Equal(newer))
}
// The latest usage lookup must return each user's newest row even when older
// rows are inserted after it and must never widen the result set with users
// that have no usage history.
func (s *UserRepoSuite) TestGetLatestUsedAtByUserIDs_PicksLatestPerUserRegardlessOfInsertOrder() {
oldest := time.Now().Add(-48 * time.Hour).UTC().Truncate(time.Second)
middle := time.Now().Add(-24 * time.Hour).UTC().Truncate(time.Second)
newest := time.Now().Add(-time.Hour).UTC().Truncate(time.Second)
userA := s.mustCreateUser(&service.User{Email: "latest-a@example.com"})
userB := s.mustCreateUser(&service.User{Email: "latest-b@example.com"})
userWithoutUsage := s.mustCreateUser(&service.User{Email: "latest-none@example.com"})
// Insert A out of chronological order, then B with a single row.
s.mustInsertUsageLog(userA.ID, middle)
s.mustInsertUsageLog(userA.ID, newest)
s.mustInsertUsageLog(userA.ID, oldest)
s.mustInsertUsageLog(userB.ID, oldest)
got, err := s.repo.GetLatestUsedAtByUserIDs(s.ctx, []int64{userA.ID, userB.ID, userWithoutUsage.ID})
s.Require().NoError(err)
s.Require().Len(got, 2)
s.Require().Contains(got, userA.ID)
s.Require().Contains(got, userB.ID)
s.Require().NotContains(got, userWithoutUsage.ID)
s.Require().True(got[userA.ID].Equal(newest))
s.Require().True(got[userB.ID].Equal(oldest))
single, err := s.repo.GetLatestUsedAtByUserID(s.ctx, userA.ID)
s.Require().NoError(err)
s.Require().NotNil(single)
s.Require().True(single.Equal(newest))
}
func (s *UserRepoSuite) TestGetLatestUsedAtByUserIDs_EmptyInputReturnsEmptyMap() {
got, err := s.repo.GetLatestUsedAtByUserIDs(s.ctx, nil)
s.Require().NoError(err)
s.Require().NotNil(got)
s.Require().Empty(got)
got, err = s.repo.GetLatestUsedAtByUserIDs(s.ctx, []int64{})
s.Require().NoError(err)
s.Require().NotNil(got)
s.Require().Empty(got)
}
func (s *UserRepoSuite) TestListWithFilters_SortByLastUsedAtDesc_UsesUsageLogsNotLastActiveAt() {
lastUsedOlder := time.Now().Add(-6 * time.Hour).UTC().Truncate(time.Second)
lastUsedNewer := time.Now().Add(-2 * time.Hour).UTC().Truncate(time.Second)