Batch Loading
Optimize lazy collection loading by batching multiple requests into a single database query.
API Reference: SyncServer · PrismaAdapter
The Problem
Without batching, lazy collections cause N+1 queries:
// 100 users displayed
const users = useCollectionModels<User>('user')
users.forEach(user => {
// Each user's posts loaded separately
user.posts.map(p => p.title)
// 100 separate requests! 😔
})The Solution
Batch all requests into one:
import { SyncServer } from '@gluonic/server'
// Server implements batchFetch
const server = SyncServer({
database,
auth,
batchFetch: async (orgId, keys) => {
// keys: [
// { t: 'post', indexKey: 'authorId', indexVal: 'user-1' },
// { t: 'post', indexKey: 'authorId', indexVal: 'user-2' },
// ... 98 more
// ]
// Single query for all!
const posts = await prisma.post.findMany({
where: {
userId: orgId,
authorId: { in: keys.map(k => k.indexVal) }
}
})
// Group by authorId
const grouped = {}
for (const post of posts) {
const key = `post:authorId:${post.authorId}`
grouped[key] = grouped[key] || []
grouped[key].push({
t: 'post',
id: post.id,
v: post.version,
p: serialize(post)
})
}
return grouped
}
})Result: 1 request instead of 100! 🎉
Quick Implementation
For Prisma adapter with auto-config:
import { PrismaAdapter } from '@gluonic/server-prisma'
const database = PrismaAdapter({
prisma,
models: {
post: {
ownership: 'userId',
versioning: 'version',
batchIndexKeys: ['authorId', 'categoryId'] // Enable batch loading!
}
}
})
// Batch loading is automatic ✓Coming soon: Automatic batch loading configuration will be enabled by default in a future release.
See full implementation guide in existing docs or coming advanced section.
Last updated on