惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
美团技术团队
T
Tenable Blog
大猫的无限游戏
大猫的无限游戏
Schneier on Security
Schneier on Security
S
Schneier on Security
博客园_首页
C
Cyber Attacks, Cyber Crime and Cyber Security
I
Intezer
T
Tailwind CSS Blog
GbyAI
GbyAI
C
CERT Recently Published Vulnerability Notes
博客园 - 【当耐特】
IT之家
IT之家
G
Google Developers Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
Vercel News
Vercel News
Cyberwarzone
Cyberwarzone
N
News and Events Feed by Topic
Application and Cybersecurity Blog
Application and Cybersecurity Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Register - Security
The Register - Security
人人都是产品经理
人人都是产品经理
Cisco Talos Blog
Cisco Talos Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Project Zero
Project Zero
V
V2EX
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
月光博客
月光博客
Hacker News - Newest:
Hacker News - Newest: "LLM"
WordPress大学
WordPress大学
L
LangChain Blog
阮一峰的网络日志
阮一峰的网络日志
MongoDB | Blog
MongoDB | Blog
F
Full Disclosure
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
N
News and Events Feed by Topic
G
GRAHAM CLULEY
H
Hacker News: Front Page
Forbes - Security
Forbes - Security
H
Heimdal Security Blog
L
LINUX DO - 最新话题
L
Lohrmann on Cybersecurity
Apple Machine Learning Research
Apple Machine Learning Research
Help Net Security
Help Net Security
C
Cybersecurity and Infrastructure Security Agency CISA
Recent Announcements
Recent Announcements
C
Cisco Blogs
L
LINUX DO - 热门话题

ashishb.net

A day in Luxembourg - the richest country in the world I was asked to install malware during a fake interview Book summary: Breakneck - China's quest to engineer the future by Dan Wang Book summary: How to Teach Your Baby to Read Book Summary: The Discontented Little Baby Book by Pamela Douglas Introducing Amazing Sandbox - run third-party tools and AI agents securely on your machine Why software outsourcing gets a bad reputation? Book summary: The Natural Baby Sleep Solution by Polly Moore A day in Antwerp, Belgium Journey of online influencers Two days in Brussels, Belgium Shortcuts - when we love them and when we don't A visit to Rakhigarhi Three days in overhyped Paris Empty Japan, crowded Tokyo The real lock-in in GitHub is not the code, but the stars 11-day Norwegian Breakaway East Caribbean cruise Sanskrit and Sri Lankan Air Force Use REST with Open API The Achilles heel of American capitalism Costa Rica in 4 days At a juice stall in Sri Lanka A short stay at Warsaw, Poland Best practices for using Python & uv inside Docker Two days in Vilnius, Lithuania How IntelliJ IDEs waste disk space Pregnancy Why there aren't many digital nomads from India Two days in Riga, Latvia To keep your machine secure, run third-party tools inside Docker Family Ties in Your DNA: Some relatives are closer than others Doctors per capita Two days in Tallinn, Estonia Ship tools as standalone static binaries Made in America Two days in Helsinki, Finland Maintaining an Android app is a lot of work The land of good deals Two days in Oslo, Norway FastAPI vs Flask performance comparison Google Search is losing to Perplexity Two days in Dublin, Ireland Continuous integration ≠ Continuous delivery World's simplest project success heuristic London in 5 days It is hard to recommend Python in production Inflation, IRS, Credit cards, and Vendors Temu and the Chinese approach Things to do in Miami Florida Revenue vs Cost Axis Language learning as an adult The unanchored babies of the green card limbo Price variance in the United States A day in Louisville, Kentucky A surprisingly positive experience with Air India Unhospitable Airports Android: Don't use stale views USA = Union of Sales and Advertisement A day in Nashville, Tennessee Minimize Javascript in your codebase A day in Birmingham, Alabama In defense of ad-supported products Real vs artificial world The science behind Punjabi singers Hiking Mt. Fuji The Indian startup bubble is insane Repairing database on the fly for millions of users Book Summary: One up on Wall Street by Peter Lynch It is hard to recommend Google Cloud At the Prague airport Kyoto in three days Migrating from WordPress to Hugo Book summary: Sick Societies by Robert B. Edgerton Statistical outcomes require statistical games Illegal immigrants to Europe via Cairo Tokyo in three days Mobs are Status Games Writing Script matters as much as the spoken language Sri Lanka in 5 days LLMs: great for business but bad business Book Summary: Safe Haven by Mark Spitznagel Mac shortcut for typing Avagraha symbol On a bus with an asylum seeker Nicaragua in 5 days When to commit Generated code to version control Why I always buy a local SIM in a foreign country Use Makefile for Android Four days in Guadalajara, Mexico Android Navigation: Up vs Back Hotels vs Airbnb vs Hostels Currency issues in Argentina Abstractions should be deep not wide Some data on podcasting Always support compressed response in an API service A day in El Calafate - Patagonia, Argentina Hermetic docker images with Hugging Face machine learning models American Elections The sound of "ch" API services should always have usage Limits Hiking in El Chaltén - trekking capital of Argentina
API backend should use dataloaders
Ashish Bhatia · 2023-06-15 · via ashishb.net

Data Loaders allow transparent batching of requests to a data provider (e.g. database). More often than not, this leads to reduced latency and better performance without forcing an explicit batching of requests for the API users, for example, your frontend developers.

Many programmers relate data loaders to Graph QL for N+1 query patterns. I believe data loaders are a great idea any time you are building an API backend. Let me illustrate the concept with a simple example. And while I am using Go as an example, data loader implementations are available in many languages.

Let’s take a toy example of a database service that will take 50 ± 20 ms to respond to a single request. And for the sake of simplicity let’s assume it will take 2X longer to respond to a batch of up to 10 requests. All these numbers are configurable in the code below for simulation. With some experimentation, you can figure out the approximate range for your database service as well. As a concrete example, assume that given a student ID, the service returns the student’s score. And to add error flow to it, the service returns an error when the student ID is a negative number.

Let’s assume there is a DBService

1
2
3
4
5
type DBService interface {
    GetScore(studentID int) Result
    // For batched results
    GetScores(studentID []int) []Result
}

And we will implement some boilerplate web service that uses this without a data loader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Code without dataloader
package main

import (
  "context"
    "fmt"
    "math/rand"
    "net/http"
    "strconv"
    "time"
)

type DBService interface {
    GetScore(ctx context.Context, studentID int) Result
    GetScores(ctx context.Context, studentID []int) []Result
}

type Result struct {
    // Only of these will be non-nil
    Score *int
    Err   error
}

type FakeDBService struct {
}

const _baseDelay = 50 * time.Millisecond
const _delayVariance = 20 * time.Millisecond

func (f FakeDBService) GetScore(_ context.Context, studentID int) Result {
    if studentID <= 0 {
        return Result{
            nil,
            fmt.Errorf("invalid student ID"),
        }
    }
    delayVariance := time.Duration(rand.Int63n(int64(_delayVariance)))
    // Simulate processing delay
    time.Sleep(_baseDelay + delayVariance)
    // Deterministic score for demo purposes
    score := studentID * studentID
    return Result{
        &score,
        nil,
    }
}

func handler(writer http.ResponseWriter, request *http.Request) {
    fakeDBService := &FakeDBService{}
    // read student ID from request
    studentIDStr := request.URL.Query().Get("student_id")
    if studentIDStr == "" {
        writer.WriteHeader(http.StatusBadRequest)
        return
    }
    studentID, err := strconv.Atoi(studentIDStr)
    if err != nil {
        writer.WriteHeader(http.StatusBadRequest)
        return
    }
    result := fakeDBService.GetScore(request.Context(), studentID)
    if result.Err != nil {
        writer.WriteHeader(http.StatusInternalServerError)
        return
    }
    // write score to response
    _, err = writer.Write([]byte(strconv.Itoa(*result.Score)))
    if err != nil {
        writer.WriteHeader(http.StatusInternalServerError)
        return
    }
}

func main() {
    // start web server
    http.HandleFunc("/score", handler)
    fmt.Printf("Starting server on port 8080...\n")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Printf("ListenAndServe: %v\n", err)
    }
}

Now, our goal is to add data loaders here, let’s use Go Modules for that

1
2
3
4
# In the same dir containing test_main.go
$ go mod init example.com/m
$ go mod tidy
$ go get -u github.com/graph-gophers/dataloader

Now, let’s add the fake/demo batch reader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func (f FakeDBService) GetScores(_ context.Context, studentIDs []int) []Result {
    fmt.Printf("GetScores called with student IDs: %+v\n", studentIDs)
    result := make([]Result, 0, len(studentIDs))
    for _, studentID := range studentIDs {
        if studentID <= 0 {
            result = append(result, Result{nil, fmt.Errorf("invalid student ID")})
        } else {
            // Deterministic score for demo purposes
            score := studentID * studentID
            result = append(result, Result{&score, nil})
        }
    }
    delayVariance := time.Duration(rand.Int63n(int64(_delayVariance)))
    // Simulate processing delay
    time.Sleep(2 * (_baseDelay + delayVariance))
    return result
}

And add a batch loader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
type FakeDBServiceWithBatching struct {
    dbService  DBService
    dataloader *dataloader.Loader
}

// This is where the magic of batching configuration happens
func newDBServiceWithBatching(dbService DBService) *FakeDBServiceWithBatching {
    // setup batch function - the first Context passed to the Loader's Load
    // function will be provided when the batch function is called.
    batchFn := func(ctx context.Context, keys dataloader.Keys) []*dataloader.Result {
        results := make([]*dataloader.Result, 0, len(keys))
        dbResults := dbService.GetScores(ctx, getStudentIDs(keys))
        for _, dbResult := range dbResults {
            results = append(results, &dataloader.Result{Data: dbResult, Error: dbResult.Err})
        }
        return results
    }

    return &FakeDBServiceWithBatching{
        dbService: dbService,
        dataloader: dataloader.NewBatchedLoader(batchFn,
            dataloader.WithClearCacheOnBatch(),
            dataloader.WithWait(10*time.Millisecond),
            dataloader.WithBatchCapacity(10)),
    }
}

// This transparently batches calls to the underlying DBService
// at most 10 requests - configured via dataloader.WithBatchCapacity
// and at most 10 ms of batch filling time  - configured via dataloader.WithWait
func (f FakeDBServiceWithBatching) GetScore(ctx context.Context, studentID int) Result {
    thunk := f.dataloader.Load(ctx, newIntKey(studentID))
    result, err := thunk()
    if err != nil {
        return Result{nil, err}
    }
    return Result{
        Score: result.(Result).Score,
        Err:   nil,
    }
}

func (f FakeDBServiceWithBatching) GetScores(ctx context.Context, studentID []int) []Result {
    return f.dbService.GetScores(ctx, studentID)
}

// Unnecessary boilerplate that will go away with Go Generics eventually

func getStudentIDs(keys dataloader.Keys) []int {
    studentIDs := make([]int, 0, len(keys))
    for _, key := range keys {
        studentIDs = append(studentIDs, key.Raw().(int))
    }
    return studentIDs
}

type IntKey struct {
    Key int
}

func newIntKey(key int) IntKey {
    return IntKey{key}
}

func (i IntKey) String() string {
    return fmt.Sprintf("%d", i.Key)
}

func (i IntKey) Raw() interface{} {
    return i.Key
}

Now, replace FakeDBService with FakeDBServiceWithBatching

1
fakeDBService := newDBServiceWithBatching(FakeDBService{})

That’s it, now, your service is ready for implicit batch requests!

You can test it by running Go Routines, for example,

Replace

1
result := fakeDBService.GetScore(request.Context(), studentID)

with

1
2
3
4
5
go fakeDBService.GetScore(request.Context(), 1)
go fakeDBService.GetScore(request.Context(), 5)
go fakeDBService.GetScore(request.Context(), 10)
go fakeDBService.GetScore(request.Context(), 21)
result := fakeDBService.GetScore(request.Context(), studentID)

And this will print the log

1
GetScores called with student IDs: [999 1 21 10 5]

Now, of course, you might wonder if this would batch on a per-request basis and that’s because that’s how we configured it. We can always use request.Background() and then this would batch multiple requests into one. And that’s usually best for an API service.