Infinite Scroll Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Infinite Scroll runs in O(n) time and O(n) space, in Go as in every other language.
- ✓database/sql covers the whole server half. DB.QueryContext ties the query to the request's context so a disconnect cancels it, Rows.Next and Rows.Scan walk the result one row at a time without materialising a slice, Rows.Err reports what Next swallowed, and Rows.Close returns the connection to the pool.
- ✓defer rows.Close() goes on the line immediately after the error check, never later, and reviewers count that as a hard rule rather than a style preference.
- ✓The Go trap: rows.Next() returns false at the end of the result and also when iteration fails partway, and Scan never sees the difference because the loop simply ends.
- ✓json.Marshal copies its scratch buffer into a fresh []byte on every call, so marshalling row by row allocates row by row; Encoder.Encode writes that buffer straight to the ResponseWriter and skips the copy.
What Infinite Scroll actually is
Infinite Scroll in Go: what you actually reach for
Go implementation
package feed
import (
"database/sql"
"encoding/json"
"net/http"
"strconv"
)
type Tremor struct {
ID int64 `json:"id"`
ObservedAt string `json:"observedAt"`
Magnitude float64 `json:"magnitude"`
}
const pageSize = 50
const query = "SELECT id, observed_at, magnitude FROM tremors WHERE (observed_at, id) > ($1, $2) ORDER BY observed_at, id LIMIT $3"
// StreamPage emits newline-delimited JSON as rows arrive, not one buffered slice.
func StreamPage(w http.ResponseWriter, r *http.Request, db *sql.DB) {
afterID, _ := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
rows, err := db.QueryContext(r.Context(), query, r.URL.Query().Get("ts"), afterID, pageSize)
if err != nil {
http.Error(w, "query failed", http.StatusInternalServerError)
return
}
defer rows.Close() // any early return without this pins a pooled connection
w.Header().Set("Content-Type", "application/x-ndjson")
flusher, canFlush := w.(http.Flusher)
enc := json.NewEncoder(w) // Encode appends the newline that makes it NDJSON
var t Tremor // one heap escape, not one per row (see perf)
for rows.Next() {
if err := rows.Scan(&t.ID, &t.ObservedAt, &t.Magnitude); err != nil {
return
}
if err := enc.Encode(&t); err != nil {
return // reader hung up mid-page
}
if canFlush {
flusher.Flush()
}
}
// Next reports false at end of rows AND on a mid-stream failure.
if err := rows.Err(); err != nil {
http.Error(w, "stream failed", http.StatusInternalServerError)
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Infinite Scroll?
database/sql covers the whole server half. DB.QueryContext ties the query to the request's context so a disconnect cancels it, Rows.Next and Rows.Scan walk the result one row at a time without materialising a slice, Rows.Err reports what Next swallowed, and Rows.Close returns the connection to the pool. encoding/json contributes Encoder.Encode, which writes straight to an io.Writer and appends a newline, giving you newline-delimited JSON for free. net/http supplies the Flusher interface for pushing each row out, and strconv parses the cursor's numeric half.
What is the most common Go mistake when implementing Infinite Scroll?
rows.Next() returns false at the end of the result and also when iteration fails partway, and Scan never sees the difference because the loop simply ends. A page a network blip truncated at row twelve is byte-identical to a page that genuinely had twelve rows: it goes out with a 200 and a valid-looking cursor, the client asks for the next page, and the missing rows are gone permanently with nothing logged. rows.Err() after the loop is the only place that error is reachable. Its sibling is returning early without Close, which keeps a connection checked out until GC and deadlocks the endpoint at MaxOpenConns.
How does Infinite Scroll actually perform in Go?
json.Marshal copies its scratch buffer into a fresh []byte on every call, so marshalling row by row allocates row by row; Encoder.Encode writes that buffer straight to the ResponseWriter and skips the copy. Scan takes ...any, and taking the address of a value that is passed to an interface parameter forces it to the heap, so declaring the destination struct above the loop costs one escape for the whole response while declaring it inside costs one per row. Flushing after every row is a write syscall per row. SetMaxOpenConns is the real ceiling here, since each in-flight page holds its connection for the entire response rather than just the query. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.