Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(insights): run product analytics home queries in parallel (#117588)

Daniel Parker660cdb137e53
diff --git a/frontend/src/lib/utils/concurrencyController.test.ts b/frontend/src/lib/utils/concurrencyController.test.ts
index 2e31018734b2..a5f925a80f9d 100644
--- a/frontend/src/lib/utils/concurrencyController.test.ts
+++ b/frontend/src/lib/utils/concurrencyController.test.ts
@@ -5,12 +5,14 @@ import { delay } from 'lib/utils/async'
import { ConcurrencyController } from './concurrencyController'
describe('concurrencyController', () => {
- const setup = (): {
+ const setup = (
+ options?: ConstructorParameters<typeof ConcurrencyController>[1]
+ ): {
concurrencyController: ConcurrencyController
results: string[]
run: (n: number, priority: number, abortController?: AbortController) => Promise<number>
} => {
- const concurrencyController = new ConcurrencyController(1)
+ const concurrencyController = new ConcurrencyController(1, options)
const results: string[] = []
const run = async (n: number, priority: number, abortController?: AbortController): Promise<number> => {
return concurrencyController.run({
@@ -35,12 +37,15 @@ describe('concurrencyController', () => {
expect(results).toEqual(['enter 1', 'exit 1', 'enter 2', 'exit 2', 'enter 3', 'exit 3', 'enter 4', 'exit 4'])
})
- it('should eagerly execute the first item regardless of priority', async () => {
- const { run, results } = setup()
+ it.each([
+ ['eagerly executes the first item regardless of priority', false, [4, 1, 2, 3]],
+ ['starts items added in the same task by priority when batched', true, [1, 2, 3, 4]],
+ ])('%s', async (_, batchStart, expectedOrder) => {
+ const { run, results } = setup({ batchStart })
await Promise.allSettled([run(4, 4), run(1, 1), run(3, 3), run(2, 2)])
- expect(results).toEqual(['enter 4', 'exit 4', 'enter 1', 'exit 1', 'enter 2', 'exit 2', 'enter 3', 'exit 3'])
+ expect(results).toEqual(expectedOrder.flatMap((n) => [`enter ${n}`, `exit ${n}`]))
})
it('should not start a new item if the item has been aborted', async () => {
diff --git a/frontend/src/lib/utils/concurrencyController.ts b/frontend/src/lib/utils/concurrencyController.ts
index db7f8b9aeb42..ddd89793e522 100644
--- a/frontend/src/lib/utils/concurrencyController.ts
+++ b/frontend/src/lib/utils/concurrencyController.ts
@@ -60,8 +60,16 @@ export class ConcurrencyController {
(a, b) => a._priority < b._priority
)
- constructor(concurrencyLimit: number) {
+ private _batchStart: boolean
+ private _startScheduled = false
+
+ /**
+ * @param batchStart Wait one task before starting work, so items added in the same render start by priority
+ * instead of in arrival order.
+ */
+ constructor(concurrencyLimit: number, { batchStart = false }: { batchStart?: boolean } = {}) {
this._concurrencyLimit = concurrencyLimit
+ this._batchStart = batchStart
}
/**
@@ -87,7 +95,11 @@ export class ConcurrencyController {
this._queue.add(item)
- this._tryRunNext()
+ if (this._batchStart) {
+ this._scheduleStart()
+ } else {
+ this._tryRunNext()
+ }
return item._promise
}
@@ -105,6 +117,19 @@ export class ConcurrencyController {
}
}
+ private _scheduleStart(): void {
+ if (this._startScheduled) {
+ return
+ }
+ this._startScheduled = true
+ setTimeout(() => {
+ this._startScheduled = false
+ while (this._current.length < this._concurrencyLimit && !this._queue.isEmpty()) {
+ this._runNext()
+ }
+ }, 0)
+ }
+
_tryRunNext(): void {
if (this._current.length < this._concurrencyLimit) {
this._runNext()
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
index 6ac7f1eca5e1..ac64a6c6ccc0 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
@@ -191,6 +191,7 @@ const accountsTableConcurrencyController = new ConcurrencyController(2)
const webAnalyticsConcurrencyController = new ConcurrencyController(6)
const webAnalyticsPreAggConcurrencyController = new ConcurrencyController(6)
const marketingAnalyticsConcurrencyController = new ConcurrencyController(6)
+const productAnalyticsHomeConcurrencyController = new ConcurrencyController(6, { batchStart: true })
function getConcurrencyController(query: DataNode, currentTeam: TeamType): ConcurrencyController {
if (isAccountsTableQuery(query)) {
@@ -204,6 +205,10 @@ function getConcurrencyController(query: DataNode, currentTeam: TeamType): Concu
return marketingAnalyticsConcurrencyController
}
+ if (activeScene === Scene.SavedInsights) {
+ return productAnalyticsHomeConcurrencyController
+ }
+
if (
[
Scene.WebAnalytics,
diff --git a/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsx b/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsx
index b1001791a1d3..98948199c627 100644
--- a/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsx
@@ -23,9 +23,10 @@ interface HomeTabChartCardProps {
size: 'primary' | 'supporting' | 'ranking'
control?: ReactNode
source?: string
+ loadPriority: number
}
-export function HomeTabChartCard({ option, size, control, source }: HomeTabChartCardProps): JSX.Element {
+export function HomeTabChartCard({ option, size, control, source, loadPriority }: HomeTabChartCardProps): JSX.Element {
const { currentTeamId } = useValues(teamLogic)
const { shouldShowSampleData } = useValues(sampleDataStateLogic)
const sampleData = useMemo(
@@ -43,7 +44,7 @@ export function HomeTabChartCard({ option, size, control, source }: HomeTabChart
uniqueKey={`HomeTab.${currentTeamId}.${chartKey}`}
context={{
insightProps: {
- loadPriority: 0,
+ loadPriority,
dashboardItemId: homeTabChartInsightId(currentTeamId, chartKey),
dataNodeCollectionId: homeTabDataCollectionId(currentTeamId),
query: option.query,
diff --git a/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx b/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx
index ead9633f8041..46ed25140088 100644
--- a/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx
@@ -15,7 +15,8 @@ import { teamLogic } from 'scenes/teamLogic'
import trendsNumber from '~/mocks/fixtures/api/projects/team_id/insights/trendsNumber.json'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
import { performQuery } from '~/queries/query'
-import { isInsightQueryNode, isTrendsQuery } from '~/queries/utils'
+import type { DataNode } from '~/queries/schema/schema-general'
+import { isInsightQueryNode, isRetentionQuery, isTrendsQuery } from '~/queries/utils'
import { initKeaTests } from '~/test/init'
import { ChartDisplayType } from '~/types'
@@ -94,34 +95,30 @@ describe('HomeTabDefault query reuse', () => {
await waitFor(() => expect(collection.values.areAnyLoading).toBe(false))
})
- it('loads totals and full charts before standalone trends', async () => {
+ it('loads totals and the primary chart, then the sparklines, then the charts below them', async () => {
const response = { results: [{ ...trendsNumber.result[0], aggregated_value: 10 }] }
const pendingTrend = promiseResolveReject<typeof response>()
- mockedQuery.mockImplementation(async (query) => {
- if (isTrendsQuery(query) && query.compareFilter?.compare === false && !query.trendsFilter) {
- return pendingTrend.promise
- }
- return response
- })
+ const isSparkline = (query: DataNode): boolean =>
+ isTrendsQuery(query) && query.compareFilter?.compare === false && !query.trendsFilter
+ const isLowerChart = (query: DataNode): boolean =>
+ isRetentionQuery(query) || (isTrendsQuery(query) && !!query.breakdownFilter)
+ mockedQuery.mockImplementation(async (query) => (isSparkline(query) ? pendingTrend.promise : response))
const { container } = render(<HomeTabDefault />)
const collection = dataNodeCollectionLogic({ key: homeTabDataCollectionId(teamLogic.values.currentTeamId) })
try {
- await waitFor(() => expect(mockedQuery).toHaveBeenCalledTimes(12))
+ await waitFor(() => expect(mockedQuery).toHaveBeenCalledTimes(7))
for (const tile of container.querySelectorAll('[data-attr^="home-tab-metric-"]')) {
expect(tile).toHaveAttribute('aria-busy', 'false')
}
- expect(
- mockedQuery.mock.calls
- .slice(0, 11)
- .some(
- ([query]) =>
- isTrendsQuery(query) && query.compareFilter?.compare === false && !query.trendsFilter
- )
- ).toBe(false)
+ const calls = mockedQuery.mock.calls.map(([query]) => query)
+ expect(calls.slice(0, 6).some(isSparkline)).toBe(false)
+ expect(isSparkline(calls[6])).toBe(true)
+ expect(calls.some(isLowerChart)).toBe(false)
} finally {
pendingTrend.resolve(response)
await waitFor(() => expect(collection.values.areAnyLoading).toBe(false))
}
+ expect(mockedQuery.mock.calls.slice(-5).every(([query]) => isLowerChart(query))).toBe(true)
})
it('hides old trend values when the new total loads before the new trend', async () => {
diff --git a/products/product_analytics/frontend/insights/home/HomeTabDefault.tsx b/products/product_analytics/frontend/insights/home/HomeTabDefault.tsx
index 4f06258ca016..8cf903f51113 100644
--- a/products/product_analytics/frontend/insights/home/HomeTabDefault.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeTabDefault.tsx
@@ -116,6 +116,7 @@ export function HomeTabDefault({ dashboardActions }: { dashboardActions?: ReactN
option={primaryChart}
size="primary"
source="Pageviews and screen views"
+ loadPriority={0}
/>
<section className="flex flex-col gap-3" aria-label="What people do">
@@ -128,6 +129,7 @@ export function HomeTabDefault({ dashboardActions }: { dashboardActions?: ReactN
key={contentChart.key}
option={contentChart}
size="ranking"
+ loadPriority={2}
source={selectedContentKey === 'top_pages' ? 'Pageviews' : 'Screen views'}
control={
<LemonSelect
@@ -143,7 +145,7 @@ export function HomeTabDefault({ dashboardActions }: { dashboardActions?: ReactN
/>
}
/>
- <HomeTabChartCard option={eventsChart} size="ranking" source="Captured events" />
+ <HomeTabChartCard option={eventsChart} size="ranking" source="Captured events" loadPriority={2} />
</div>
</section>
@@ -156,13 +158,14 @@ export function HomeTabDefault({ dashboardActions }: { dashboardActions?: ReactN
option={option}
size="supporting"
source="Pageviews and screen views"
+ loadPriority={3}
/>
))}
</div>
</section>
<div className="grid min-w-0 grid-cols-1 gap-3 @min-[44rem]/home-overview:grid-cols-2">
- <HomeTabChartCard option={retentionChart} size="supporting" source="Pageviews" />
+ <HomeTabChartCard option={retentionChart} size="supporting" source="Pageviews" loadPriority={4} />
<HomeTabExplore />
</div>
</div>