go
32 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package paging
import (
"encoding/base64"
"encoding/json"
"time"
)
type Cursor struct {
CreatedAt time.Time `json:"created_at"`
ID string `json:"id"`
}
func Encode(c Cursor) (string, error) {
b, err := json.Marshal(c)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
func Decode(token string) (Cursor, error) {
b, err := base64.RawURLEncoding.DecodeString(token)
if err != nil {
return Cursor{}, err
}
var c Cursor
if err := json.Unmarshal(b, &c); err != nil {
return Cursor{}, err
}
return c, nil
}
1 file · go
Explain with highlit
Offset pagination (LIMIT/OFFSET) is fine until it isn’t: it gets slow on large tables and it produces weird duplicates when rows are inserted between pages. For APIs I prefer cursor pagination with an opaque token. The token encodes the last seen (created_at, id) and the query uses that tuple for stable ordering. The important detail is the “tie breaker” field (id) so you never skip rows when multiple items share the same timestamp. I make the cursor opaque by base64-encoding JSON; you can also sign it if tampering matters. This pattern keeps DB performance predictable and makes frontend infinite scroll stable. It’s also easier to cache because page boundaries don’t shift as data changes.
Related snips
go
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
go
observability
build
by Leah Thompson
1 tab
ruby
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
jwt
authentication
api
by Kai Nakamura
2 tabs
ruby
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
rails
caching
http-caching
by Alex Kumar
1 tab
ruby
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
rails
turbo
hotwire
by codesnips
4 tabs
go
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
go
postgres
transactions
by Leah Thompson
1 tab
graphql
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
createdAt: String!
GraphQL API with Spring Boot
java
graphql
spring-boot
by David Kumar
3 tabs
Share this code
Here's the card — post it anywhere.