Speculatively
Package speculatively provides a simple mechanism to re-execute a task in parallel only after some initial timeout has elapsed.
Install / Use
/learn @mccutchen/SpeculativelyREADME
speculatively
Package speculatively provides a simple mechanism to speculatively execute a
task in parallel only after some initial timeout has elapsed:
// An example task that will wait for a random amount of time before returning
task := func(ctx context.Context) (string, error) {
delay := time.Duration(float64(250*time.Millisecond) * rand.Float64())
select {
case <-time.After(delay):
return "success", nil
case <-ctx.Done():
return "timeout", ctx.Err()
}
}
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
// If task doesn't return within 20ms, it will be executed again in parallel
result, err := speculatively.Do(ctx, 20*time.Millisecond, task)
This was inspired by the "Defeat your 99th percentile with speculative task" blog post, which describes it nicely:
The inspiration came from BigData world. In Spark when task execution runs suspiciously long the application master starts the same task speculatively on a different executor but it lets the long running tasks to continue. The solution looked elegant:
Service response time limit is 50ms.
If the first attempt doesn’t finish within 25ms start a new one, but keep the first thread running.
Wait for either thread to finish and take result from the first one ready.
The speculative tasks implemented here are similar to "hedged requests" as described in The Tail at Scale and implemented in the Query example function in Go Concurrency Patterns: Timing out, moving on, but they a) have no knowledge of different replicas and b) wait for a caller-controlled timeout before launching additional tasks.
Related Skills
xurl
345.9kA CLI tool for making authenticated requests to the X (Twitter) API. Use this skill when you need to post tweets, reply, quote, search, read posts, manage followers, send DMs, upload media, or interact with any X API v2 endpoint.
wanwu
4.2kChina Unicom's Yuanjing Wanwu Agent Platform is an enterprise-grade, multi-tenant AI agent development platform. It helps users build applications such as intelligent agents, workflows, and rag, and also supports model management. The platform features a developer-friendly license, and we welcome all developers to build upon the platform.
gin-vue-admin
24.5k🚀Vite+Vue3+Gin拥有AI辅助的基础开发平台,企业级业务AI+开发解决方案,内置mcp辅助服务,内置skills管理,支持TS和JS混用。它集成了JWT鉴权、权限管理、动态路由、显隐可控组件、分页封装、多点登录拦截、资源权限、上传下载、代码生成器、表单生成器和可配置的导入导出等开发必备功能。
kubeshark
11.9keBPF-powered network observability for Kubernetes. Indexes L4/L7 traffic with full K8s context, decrypts TLS without keys. Queryable by AI agents via MCP and humans via dashboard.
