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

推荐订阅源

有赞技术团队
有赞技术团队
M
MIT News - Artificial intelligence
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
量子位
S
SegmentFault 最新的问题
V
Visual Studio Blog
博客园 - 【当耐特】
Apple Machine Learning Research
Apple Machine Learning Research
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
小众软件
小众软件
Stack Overflow Blog
Stack Overflow Blog
Vercel News
Vercel News
D
Docker
J
Java Code Geeks
博客园 - 三生石上(FineUI控件)
博客园 - Franky
Recent Announcements
Recent Announcements
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MongoDB | Blog
MongoDB | Blog
D
DataBreaches.Net
Y
Y Combinator Blog
云风的 BLOG
云风的 BLOG
V
V2EX

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
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.