Skip to content

Segment builds page contacts with LIMIT/OFFSET, so a full build is quadratic in the number of contacts #571

Closed

Description

@mm0nst3r

Version: v41.0 (the same code is on the default branch at v43.0)

What happens

SegmentBuildProcessor.Process (internal/service/segment_build_processor.go) walks every contact in batches of 100 and fetches each batch with contactRepo.GetBatchForSegment(ctx, workspaceID, state.ContactOffset, p.batchSize). That query (internal/repository/contact_postgres.go) is:

SELECT email
FROM contacts
ORDER BY email ASC
LIMIT $1 OFFSET $2

PostgreSQL has to walk the contacts_pkey index from its start for every batch and discard OFFSET rows, so batch k costs O(k) and one full build costs O(n²/batch).

Measured on a workspace with 670,488 contacts (PostgreSQL 17, warm cache)

OFFSET Execution time Buffers touched
50,000 46 ms 45,132
335,000 227 ms 310,827
650,000 265 ms 611,913

One build is about 6,700 batches. Segments with relative-date conditions are recomputed daily, and they are all due at the same time, so the builds run concurrently. With 11 such segments the daily recompute keeps a 4-CPU PostgreSQL saturated for about 95 minutes, and each build_segment task is paused by its timeout hundreds of times ("Approaching timeout, pausing segment build"). The segment predicate itself is cheap: evaluating it for a 20,000-contact slice takes about half a second.

Expected

Batch cost independent of position, for example keyset pagination on the primary key, keeping the last email in the task state instead of a numeric offset:

SELECT email
FROM contacts
WHERE email > $2
ORDER BY email ASC
LIMIT $1

This also avoids skipped or repeated contacts when contacts are inserted or deleted during a build, which an offset cannot guarantee.

Activity

  1. self-assigned this
    on Nov 14, 2026
  2. pierre-b commented on Nov 14, 2026

    @pierre-b
    Contributor

    Hi @mm0nst3r , thanks for the request, I'm actually. working on a major release with tons of improvements, it should be fixed very soon!

  3. pierre-b commented on Nov 19, 2026

    @pierre-b
    Contributor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions