Collect, Format, and Group Paginated Activity Feeds

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are integrating with two external service callbacks to consume, display, and aggregate an activity stream:

  • fetch_page(page_number: int) -> Tuple[int, List[Activity]]: requests a 1-indexed page (1, 2, 3, ...) and returns (total_count, page_activities), where total_count is the server's reported item count across the whole stream and page_activities is the slice of activity records on that page.
  • get_user_name(user_id: object) -> str: resolves a user identifier into that user's human-readable display name.

Each Activity is a dictionary containing "type" (str), "name" (str), and "user_id" (a hashable user identifier), along with optional extra fields such as "id".

Implement the Clump class and the five pipeline functions declared in starter.py:

  1. Clump(activity_type: str, name: str)
    • Stores attributes self.type (str), self.name (str), and self.activities (List[Activity], initialized to an empty list).
  2. fetch_all_activities(fetch_page: FetchPage) -> List[Activity]
    • Requests pages 1, 2, ... in order and returns every activity concatenated in page order.
    • Stop immediately as soon as at least total_count activities have been collected or when fetch_page returns an empty page [].
  3. format_activity(activity: Activity, user_name: str) -> str
    • Formats a single record as "<type>: <name> by <user_name>".
  4. print_activities(activities: List[Activity], get_user_name: GetUserName) -> List[str]
    • Prints one formatted line per activity (using print(...)) with the resolved display name instead of the raw user_id, and returns the list of formatted lines in order.
    • Call get_user_name at most once per distinct user_id.
  5. group_into_clumps(activities: List[Activity]) -> List[Clump]
    • Collects all activities sharing an identical (type, name) pair into a single Clump, even if they arrived on different pages.
    • Clump instances must be returned in the order their first matching activity appeared, and clump.activities must preserve the original order of those activities.
  6. process_activities(fetch_page: FetchPage, get_user_name: GetUserName) -> List[Clump]
    • Fetches all paginated activities, prints every formatted activity line with resolved user names, and returns the grouped List[Clump].

Examples

Example 1

Input:

Pages (page_size = 2, total_count = 5):
  fetch_page(1) -> (5, [
    {"id": 101, "type": "deploy", "name": "BillingService", "user_id": 41},
    {"id": 102, "type": "review", "name": "BillingService", "user_id": 42}
  ])
  fetch_page(2) -> (5, [
    {"id": 103, "type": "deploy", "name": "BillingService", "user_id": 42},
    {"id": 104, "type": "alert",  "name": "SearchIndex",    "user_id": 41}
  ])
  fetch_page(3) -> (5, [
    {"id": 105, "type": "review", "name": "BillingService", "user_id": 41}
  ])

Users:
  get_user_name(41) -> "Maya"
  get_user_name(42) -> "Liam"

Printed Output:

deploy: BillingService by Maya
review: BillingService by Liam
deploy: BillingService by Liam
alert: SearchIndex by Maya
review: BillingService by Maya

Returned Clumps:

[
  Clump(type="deploy", name="BillingService", activities=[id=101, id=103]),
  Clump(type="review", name="BillingService", activities=[id=102, id=105]),
  Clump(type="alert",  name="SearchIndex",    activities=[id=104])
]

Walk-through: fetch_all_activities calls pages 1, 2, and 3, collecting 5 items (5 >= 5, so page 4 is never requested). print_activities resolves user 41 ("Maya") and user 42 ("Liam") once each and reuses the cached names for the remaining records. Finally, group_into_clumps merges matching (type, name) pairs across page boundaries—for example, ("deploy", "BillingService") combines id=101 from page 1 with id=103 from page 2.

Example 2

Input:

Pages (page_size = 2, total_count = 4):
  fetch_page(1) -> (4, [
    {"id": 1, "type": "merge",    "name": "AuthAPI", "user_id": 9},
    {"id": 2, "type": "merge",    "name": "WebApp",  "user_id": 9}
  ])
  fetch_page(2) -> (4, [
    {"id": 3, "type": "rollback", "name": "AuthAPI", "user_id": 15},
    {"id": 4, "type": "merge",    "name": "AuthAPI", "user_id": 15}
  ])

Users:
  get_user_name(9)  -> "Noah"
  get_user_name(15) -> "Priya"

Printed Output:

merge: AuthAPI by Noah
merge: WebApp by Noah
rollback: AuthAPI by Priya
merge: AuthAPI by Priya

Returned Clumps:

[
  Clump(type="merge",    name="AuthAPI", activities=[id=1, id=4]),
  Clump(type="merge",    name="WebApp",  activities=[id=2]),
  Clump(type="rollback", name="AuthAPI", activities=[id=3])
]

Walk-through: Because 4 is an exact multiple of the page size 2, fetch_all_activities stops right after page 2 without making a wasted request for page 3. Sharing only "type" ("merge" on "AuthAPI" vs. "WebApp") or sharing only "name" ("merge" vs. "rollback" on "AuthAPI") produces distinct clumps.

Constraints

  • 0 <= total_count <= 10^5
  • Page numbers are 1-based (1, 2, 3, ...).
  • If records were removed on the server while paging so fewer than total_count items exist, the first out-of-range fetch_page call returns (total_count, []) and pagination must terminate cleanly.
  • activity["type"], activity["name"], and user display names are strings (which may be empty "").
  • activity["user_id"] is hashable; get_user_name must be invoked at most once per unique user_id during print_activities.
  • Expected local CPU time is O(n) for n fetched activities, using O(n + u) memory for u distinct users.

Step-by-step walkthrough

  1. Restate the problem and pin down the API contracts

    We are building a small client pipeline on top of two external service callbacks:

    1. Paginated feed callback: fetch_page(page) returns (total_count, page_items) for 1-based page numbers 1, 2, 3, .... Instead of sending a huge stream in one payload, a paginated API slices records into fixed-size pages.
    2. User lookup callback: get_user_name(user_id) returns the human-readable display name (such as "Maya") for a raw user ID (such as 41).

    Our code needs to: - Fetch every activity across all pages in exact page order, - Print one line per activity showing the user's display name instead of their raw ID: "<type>: <name> by <user_name>", and - Group all fetched activities into Clump objects, where each Clump holds type, name, and activities (all activities sharing that exact (type, name) pair, even when they arrived on different pages).

    Passing fetch_page and get_user_name in as function arguments (dependency injection—supplying external services as parameters rather than hardcoding global network calls) keeps the logic modular and lets tests simulate empty, multi-page, or inconsistent servers in memory.

  2. See why the naive version wastes network calls and work

    Suppose the stream has n = 10,000 activities generated by u = 50 engineers across k = 200 distinct (type, name) pairs:

    • Pagination trap: If you loop only while len(activities) < total_count, and an item is deleted while you are paging through, the last page comes back empty [] while len(activities) is 9,999 < 10,000—trapping your program in an infinite loop! Conversely, if you loop only until an empty page arrives, an exact multiple (like 4 items at 2 per page) wastes an extra network trip fetching an empty page 3.
    • Repeated user lookups: Calling get_user_name(activity["user_id"]) directly inside the print loop fires 10,000 remote lookups when only 50 distinct users exist—9,950 redundant round trips!
    • Linear clump scanning: Scanning a list of existing clumps from start to finish for every activity takes O(n × k) comparisons (2,000,000 checks here) instead of O(n) with a dictionary.

    Fixing all three takes two loop guards and two dictionaries.

  3. Fetch all pages safely with two stop conditions

    Start at page = 1 and stop the loop as soon as either condition triggers:

    1. Empty-page guard (if not page_items: break): If the server returns [], there is nothing left to read—stop immediately even if total_count claimed more items existed.
    2. Target-count guard (if len(activities) >= total_count: break): Once we have collected at least total_count items, we already have the final page—stop right away without requesting an empty trailing page.
      Suppose 4 items total, page_size = 2 (Example 2):
      fetch_page(1) -> (4, [item1, item2])          collected = 2 < 4   -> continue to page 2
      fetch_page(2) -> (4, [item3, item4])          collected = 4 >= 4  -> STOP! (page 3 never called)
    
      Suppose server stale total_count = 10, but only 4 items actually exist (page_size = 3):
      fetch_page(1) -> (10, [item1, item2, item3])  collected = 3 < 10  -> continue
      fetch_page(2) -> (10, [item4])                collected = 4 < 10  -> continue
      fetch_page(3) -> (10, [])                     page_items is empty -> STOP! (no infinite loop)
    
    from typing import Callable, Dict, List, Tuple
    
    Activity = Dict[str, object]
    FetchPage = Callable[[int], Tuple[int, List[Activity]]]
    
    
    def fetch_all_activities(fetch_page: FetchPage) -> List[Activity]:
        """Fetch pages 1, 2, ... until total_count items are gathered or an empty page arrives."""
        # activities: flat list of all fetched Activity dicts in exact page order
        activities: List[Activity] = []
        page = 1
    
        while True:
            total_count, page_items = fetch_page(page)
    
            # Guard 1: stop on an empty page even if total_count promised more items,
            # preventing an infinite loop when items are deleted mid-scan or total_count is buggy.
            if not page_items:
                break
    
            activities.extend(page_items)
    
            # Guard 2: stop as soon as we have collected at least total_count items,
            # avoiding a wasted network call for an empty trailing page when n is a multiple of page_size.
            if len(activities) >= total_count:
                break
    
            page += 1
    
        return activities
    
  4. Print activities using a per-user name cache

    Store resolved display names in a dictionary name_cache mapping user_id -> user_name. The first time we see user_id = 41, we call get_user_name(41) and save "Maya" in name_cache[41]. Every later activity by user 41 reads "Maya" straight from memory in O(1) time.

    Check if user_id not in name_cache rather than if not name_cache.get(user_id). Why? If a user's display name happens to be the empty string "", not "" is True in Python—which would trick a truthiness check into calling the remote lookup over and over!

    from typing import Callable, Dict, List
    
    Activity = Dict[str, object]
    GetUserName = Callable[[object], str]
    
    
    def format_activity(activity: Activity, user_name: str) -> str:
        """Format one activity line with the resolved user display name instead of user_id."""
        return f"{activity['type']}: {activity['name']} by {user_name}"
    
    
    def print_activities(activities: List[Activity], get_user_name: GetUserName) -> List[str]:
        """Resolve user names with a per-user cache, print each formatted activity, and return the lines."""
        # name_cache: maps user_id -> resolved user_name string, e.g. {41: "Maya", 42: "Liam"}
        name_cache: Dict[object, str] = {}
        lines: List[str] = []
    
        for activity in activities:
            user_id = activity["user_id"]
            # Use 'not in' rather than truthiness so even an empty display name "" is fetched only once.
            if user_id not in name_cache:
                name_cache[user_id] = get_user_name(user_id)
    
            user_name = name_cache[user_id]
            line = format_activity(activity, user_name)
            print(line)
            lines.append(line)
    
        return lines
    
  5. Group activities into Clumps with a tuple-keyed dictionary

    Each Clump stores self.type, self.name, and self.activities (a list initialized inside __init__ so every clump owns its own separate list). Notice we name the constructor parameter activity_type rather than type so we never shadow Python's built-in type() function, while still setting the attribute self.type as required.

    To group in one linear pass, map each 2-tuple (activity["type"], activity["name"]) to its Clump: - Why a 2-tuple instead of type + name? Concatenating strings without a guaranteed delimiter causes collisions: "ab" + "c" and "a" + "bc" both produce "abc", merging two unrelated groups! A Python tuple ("ab", "c") != ("a", "bc") keeps both fields distinct. - Why is ordering preserved automatically? In Python 3.7+, dict preserves insertion order—the order keys were first added. So list(clumps_by_key.values()) returns clumps in the exact order their first activity appeared, and appending to clump.activities preserves fetch order within each clump.

    from typing import Dict, List, Tuple
    
    Activity = Dict[str, object]
    
    
    class Clump:
        """All activities that share one (type, name) pair, kept in fetch order."""
    
        def __init__(self, activity_type: str, name: str) -> None:
            # Parameter is named activity_type to avoid shadowing Python's built-in type().
            self.type = activity_type
            self.name = name
            # activities: list of Activity dicts belonging to this (type, name) group
            self.activities: List[Activity] = []
    
        def __repr__(self) -> str:
            return f"Clump(type={self.type!r}, name={self.name!r}, activities={len(self.activities)})"
    
    
    def group_into_clumps(activities: List[Activity]) -> List[Clump]:
        """Group activities into Clump objects keyed by (type, name) in order of first appearance."""
        # clumps_by_key: maps (activity_type, activity_name) -> Clump instance
        clumps_by_key: Dict[Tuple[object, object], Clump] = {}
    
        for activity in activities:
            activity_type = str(activity["type"])
            activity_name = str(activity["name"])
            # Use a 2-tuple key so ("ab", "c") and ("a", "bc") never collide like string concatenation would.
            key: Tuple[object, object] = (activity["type"], activity["name"])
    
            if key not in clumps_by_key:
                clumps_by_key[key] = Clump(activity_type, activity_name)
    
            clumps_by_key[key].activities.append(activity)
    
        # Python dicts preserve insertion order, so clumps appear in the order their first item arrived.
        return list(clumps_by_key.values())
    
  6. Walk through Example 1 across 3 pages

    Trace Example 1 with page_size = 2, total_count = 5, and users {41: "Maya", 42: "Liam"}:

      Fetched pages:
        Page 1 -> (5, [id=101 (deploy, BillingService, u=41), id=102 (review, BillingService, u=42)])  len=2 < 5
        Page 2 -> (5, [id=103 (deploy, BillingService, u=42), id=104 (alert,  SearchIndex,    u=41)])  len=4 < 5
        Page 3 -> (5, [id=105 (review, BillingService, u=41)])                                         len=5 >= 5 -> STOP
    
      Name lookups & printed output:
        id=101 (u=41): cache miss -> get_user_name(41)="Maya" -> "deploy: BillingService by Maya"
        id=102 (u=42): cache miss -> get_user_name(42)="Liam" -> "review: BillingService by Liam"
        id=103 (u=42): cache HIT  -> "Liam"                   -> "deploy: BillingService by Liam"
        id=104 (u=41): cache HIT  -> "Maya"                   -> "alert: SearchIndex by Maya"
        id=105 (u=41): cache HIT  -> "Maya"                   -> "review: BillingService by Maya"
    
      Resulting clumps (in first-seen order):
        1. Clump(type="deploy", name="BillingService") -> [id=101, id=103]   (merged across Page 1 & Page 2!)
        2. Clump(type="review", name="BillingService") -> [id=102, id=105]   (merged across Page 1 & Page 3!)
        3. Clump(type="alert",  name="SearchIndex")    -> [id=104]
    

    Notice why process_activities fetches all pages before calling group_into_clumps: activities 101 and 103 belong to the same ("deploy", "BillingService") clump even though they arrived on separate pages.

  7. Complete solution

    from typing import Callable, Dict, List, Tuple
    
    # Activity: one activity record, e.g. {"id": 101, "type": "deploy", "name": "BillingService", "user_id": 41}
    Activity = Dict[str, object]
    # FetchPage: fetch_page(page_number) -> (total_count, page_activities), with 1-based page numbers
    FetchPage = Callable[[int], Tuple[int, List[Activity]]]
    # GetUserName: get_user_name(user_id) -> display name string, e.g. "Maya"
    GetUserName = Callable[[object], str]
    
    
    class Clump:
        """All activities that share one (type, name) pair, kept in fetch order."""
    
        def __init__(self, activity_type: str, name: str) -> None:
            # Parameter is named activity_type to avoid shadowing Python's built-in type().
            self.type = activity_type
            self.name = name
            # activities: list of Activity dicts belonging to this (type, name) group
            self.activities: List[Activity] = []
    
        def __repr__(self) -> str:
            return f"Clump(type={self.type!r}, name={self.name!r}, activities={len(self.activities)})"
    
    
    def fetch_all_activities(fetch_page: FetchPage) -> List[Activity]:
        """Fetch pages 1, 2, ... until total_count items are gathered or an empty page arrives."""
        # activities: flat list of all fetched Activity dicts in exact page order
        activities: List[Activity] = []
        page = 1
    
        while True:
            total_count, page_items = fetch_page(page)
    
            # Guard 1: stop on an empty page even if total_count promised more items,
            # preventing an infinite loop when items are deleted mid-scan or total_count is buggy.
            if not page_items:
                break
    
            activities.extend(page_items)
    
            # Guard 2: stop as soon as we have collected at least total_count items,
            # avoiding a wasted network call for an empty trailing page when n is a multiple of page_size.
            if len(activities) >= total_count:
                break
    
            page += 1
    
        return activities
    
    
    def format_activity(activity: Activity, user_name: str) -> str:
        """Format one activity line with the resolved user display name instead of user_id."""
        return f"{activity['type']}: {activity['name']} by {user_name}"
    
    
    def print_activities(activities: List[Activity], get_user_name: GetUserName) -> List[str]:
        """Resolve user names with a per-user cache, print each formatted activity, and return the lines."""
        # name_cache: maps user_id -> resolved user_name string, e.g. {41: "Maya", 42: "Liam"}
        name_cache: Dict[object, str] = {}
        lines: List[str] = []
    
        for activity in activities:
            user_id = activity["user_id"]
            # Use 'not in' rather than truthiness so even an empty display name "" is fetched only once.
            if user_id not in name_cache:
                name_cache[user_id] = get_user_name(user_id)
    
            user_name = name_cache[user_id]
            line = format_activity(activity, user_name)
            print(line)
            lines.append(line)
    
        return lines
    
    
    def group_into_clumps(activities: List[Activity]) -> List[Clump]:
        """Group activities into Clump objects keyed by (type, name) in order of first appearance."""
        # clumps_by_key: maps (activity_type, activity_name) -> Clump instance
        clumps_by_key: Dict[Tuple[object, object], Clump] = {}
    
        for activity in activities:
            activity_type = str(activity["type"])
            activity_name = str(activity["name"])
            # Use a 2-tuple key so ("ab", "c") and ("a", "bc") never collide like string concatenation would.
            key: Tuple[object, object] = (activity["type"], activity["name"])
    
            if key not in clumps_by_key:
                clumps_by_key[key] = Clump(activity_type, activity_name)
    
            clumps_by_key[key].activities.append(activity)
    
        # Python dicts preserve insertion order, so clumps appear in the order their first item arrived.
        return list(clumps_by_key.values())
    
    
    def process_activities(fetch_page: FetchPage, get_user_name: GetUserName) -> List[Clump]:
        """Fetch all paginated activities, print each with its user's name, and return grouped clumps."""
        # Phase 1: collect all pages before grouping so clumps merge items across page boundaries.
        activities = fetch_all_activities(fetch_page)
        # Phase 2: print every activity with cached user-name lookups.
        print_activities(activities, get_user_name)
        # Phase 3: bucket all activities by (type, name) while preserving order.
        return group_into_clumps(activities)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of this task like collecting every page of an engineering deployment logbook, replacing employee badge numbers with real names from a team directory, and sorting the entries into labeled folders. Because the logbook arrives one page at a time (pagination, splitting a large result list into smaller numbered chunks), you first turn pages until you have every row, look up each badge number once and jot the name on a sticky note (memoization / caching, saving previous answers in a dictionary so you never ask the same question twice), and finally drop each row into the folder matching its (type, name) label.

A naive implementation falls into three traps. First, looping strictly while len(activities) < total_count hangs forever if an item is deleted mid-read and a page comes back empty, whereas ignoring total_count makes a wasted extra network call when the item count divides evenly by the page size. Second, calling get_user_name(user_id) on every single activity fires thousands of slow network requests when the same handful of teammates created most of the events. Third, scanning existing clumps in a list to find a matching (type, name) pair takes quadratic work instead of an instant dictionary lookup.

Walk through a tiny concrete trace from Example 2 with 4 activities, page size 2, and user directory {9: "Noah", 15: "Priya"}: - Fetch pages: Page 1 returns (4, [merge AuthAPI u=9, merge WebApp u=9]) (2 < 4, keep going). Page 2 returns (4, [rollback AuthAPI u=15, merge AuthAPI u=15]) (4 >= 4, stop immediately without requesting Page 3). - Print with cached names: Activity 1 misses name_cache and fetches 9 -> "Noah"; Activity 2 hits name_cache[9] in memory with zero API calls; Activity 3 misses and fetches 15 -> "Priya"; Activity 4 hits name_cache[15], printing "merge: AuthAPI by Priya". - Group by (type, name): Walking the 4 items inserts keys into clumps_by_key in first-seen order: ("merge", "AuthAPI") gets activities [1, 4], ("merge", "WebApp") gets [2], and ("rollback", "AuthAPI") gets [3].

Complexity

Let n be the total number of activities, p be the page size, u be the number of distinct users (u <= n), and k be the number of distinct (type, name) clumps (k <= n).

  • Time: O(n) local CPU work plus ceil(n / p) page API calls and u user-name API calls. We visit each activity a constant number of times: once when extending activities across ceil(n / p) pages (plus 1 call if the feed is empty or total_count was overestimated), once when printing with an O(1) average-time dictionary lookup in name_cache (calling get_user_name only u times total), and once when grouping via an O(1) average-time tuple-key lookup in clumps_by_key.
  • Space: O(n + u). Storing the n fetched activity references in activities and across the k Clump lists uses O(n) memory (the clumps point to the same activity dictionaries rather than copying them), clumps_by_key holds k <= n entries, and name_cache holds u user names.

Edge cases

  • Empty feed ((0, []) on Page 1): The if not page_items: break guard exits on the first iteration, nothing is printed, get_user_name is never called, and [] is returned.
  • Exact multiple of page size (e.g., 4 items with page size 2): After Page 2, len(activities) == 4 >= 4, so the loop stops cleanly without requesting an empty Page 3.
  • Overestimated total_count (items deleted mid-scan or stale count): Page 3 returns [], hitting if not page_items: break instead of looping forever.
  • Underestimated total_count: Stopping at len(activities) >= total_count trusts the server's count to save one network round trip; if an API's total_count can lag behind new inserts, drop that second guard and page until not page_items.
  • Tuple-key boundary collisions (("ab", "c") vs. ("a", "bc")): Because the dictionary key is a 2-tuple (type, name) rather than type + name, pairs that concatenate to "abc" stay in separate clumps.
  • Empty string user name (""): Checking user_id not in name_cache caches "" properly instead of treating it as missing on future lookups.
  • Cross-page clumps: Activities sharing (type, name) on Page 1 and Page 3 land in the same Clump because grouping runs after all pages are collected.

Common mistakes

  • Missing the empty-page stop condition: Writing while len(activities) < total_count: alone causes an infinite loop whenever total_count exceeds the actual items available.
  • Off-by-one page numbering (0-based vs. 1-based): Starting at page = 0 on a 1-based API either duplicates Page 1, raises an error, or returns [] and aborts immediately—always confirm page numbering first.
  • Uncached get_user_name calls: Calling get_user_name on every activity turns u network calls into n network calls (the classic N+1 query problem).
  • Concatenating type + name as a string key: Collides whenever a suffix of type matches a prefix of name.
  • Using a mutable default list def __init__(self, t, n, activities=[]): In Python, default argument values are created once when class Clump is defined, which would make every Clump instance share the exact same list!

Alternative approaches

  • Adjacent (run-length) clumping: In some notification feeds (like "Liam deployed BillingService 3 times in a row"), a clump only merges consecutive activities with the same (type, name), starting a fresh clump if another event happens in between. Always clarify with your interviewer whether "clump" means global grouping (dict by key) or consecutive runs (comparing only against clumps[-1]):
def group_consecutive_runs(activities):
    clumps = []
    for activity in activities:
        if (
            not clumps
            or clumps[-1].type != activity["type"]
            or clumps[-1].name != activity["name"]
        ):
            clumps.append(Clump(str(activity["type"]), str(activity["name"])))
        clumps[-1].activities.append(activity)
    return clumps
  • Streamed printing + incremental grouping: Instead of storing a flat activities list first, print each page's items and insert them straight into clumps_by_key as each page arrives. Peak memory stays O(n) because Clump.activities still holds all items, but the first printed lines appear immediately after Page 1 finishes.

Follow-up questions

  • How would you accelerate the pipeline when the feed spans hundreds of pages and involves hundreds of distinct users? Page 1 returns (total_count, first_page), which reveals the page size p = len(first_page) and total pages ceil(total_count / p)—allowing you to fetch pages 2..k concurrently using a bounded ThreadPoolExecutor (for example, 8 worker threads) and reassemble them in page order. Apply the same bounded concurrency (or a batch get_user_names(user_ids) endpoint if available) to resolve unique user_id values in parallel before printing, and add exponential backoff (waiting 0.5 s, 1 s, 2 s, ... on HTTP 429 Too Many Requests) so parallel workers do not overwhelm rate limits.
  • What anomalies happen if new events arrive or existing ones are deleted while you are paging through the feed, and how can you prevent them? Under offset pagination (where page N slices indices (N - 1) × p through N × p - 1), inserting one new activity at index 0 pushes every existing item right by one slot—causing the last item of Page 1 to show up again as the first item of Page 2, while a deletion shifts items left and silently skips an activity! On the client side, deduplicate fetched records using a seen_ids set keyed by activity["id"]; if you control the backend API, replace page numbers with cursor (keyset) pagination (passing after_id=<last_seen_id> so each page anchors to a specific record rather than a shifting index).
  • How should the pipeline handle transient timeouts or permanently missing user records from get_user_name(user_id)? Wrap get_user_name in a small retry helper that retries transient network timeouts or 5xx errors 2–3 times with short backoff, and on permanent failure (such as 404 User Not Found) fall back gracefully to a placeholder like "Unknown User (id=42)" and cache that fallback for the rest of the run. That way, one broken user record never aborts printing or grouping thousands of valid activities, and you do not repeatedly stall on the same dead user ID.

Follow-up questions

Similar questions

More Peregrine interview questions

All 1 Peregrine questions →