This is an excerpt from my Go backend Schatzhauser with graceful shutdown:
package main
import (
"context"
"database/sql"
"fmt"
"io"
"net/http"
"os"
"os/signal"
"time"
_ "github.com/mattn/go-sqlite3"
dbpkg "schatzhauser/db"
"schatzhauser/internal/config"
"schatzhauser/internal/logger"
"schatzhauser/internal/server"
)
func run(ctx context.Context, w io.Writer, args []string) error {
// Load configuration
cfg, err := config.LoadConfig("config.toml")
if err != nil {
logger.Error("failed to load config", "err", err)
}
// Setup logging: passing in *cfg to read cfg.Debug from toml
// and set stdout to text (debug=true) or json (debug=false)
logger.Init(cfg)
logger.Info("starting schatzhauser", "debug", cfg.Debug)
// -----------------------------------------------------
// Database (SQLite)
// -----------------------------------------------------
db, err := sql.Open("sqlite3", cfg.DBPath+"?_foreign_keys=on")
if err != nil {
return fmt.Errorf("open db: %w", err)
}
// DB sanity check
if err := db.PingContext(ctx); err != nil {
return fmt.Errorf("db ping: %w", err)
}
// -----------------------------------------------------
// Run migrations (manual, SQL files)
// -----------------------------------------------------
if err := dbpkg.RunMigrations(db); err != nil {
return fmt.Errorf("migrations: %w", err)
}
// -----------------------------------------------------
// HTTP server setup
// -----------------------------------------------------
mux := http.NewServeMux()
server.RegisterRoutes(mux, db, &cfg)
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
}
// -----------------------------------------------------
// Server in goroutine + graceful shutdown
// -----------------------------------------------------
go func() {
logger.Info("listening on :8080")
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error("server error", "err", err)
}
}()
// Handle Ctrl+C
ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
defer stop()
<-ctx.Done()
logger.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
logger.Error("shutdown error", "err", err)
}
_ = db.Close()
return nil
}
func main() {
ctx := context.Background()
if err := run(ctx, os.Stdout, os.Args); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
} Rewrite this in D with vibe.d, I want to see how close we can get to Go maturity and if we get the same preemptive stackful coroutine experience in D. Push it to the limit with proper cancellation and timeouts to see what D is capable of, where the friction points are.
I am considering D as alternative to Go with fewer warts and somewhat matching Go concurrency, how viable is that goal and assessment of D, can D be a better Go if we ignore tiny D's ecosystem. I mostly appreciate goroutines, but Lua coroutine model is fine too. Looking mostly for fun and productivity.
Vibe.d is considerably more interesting than its age and popularity might suggest.
Its concurrency model is based on stackful fibers. You write ordinary sequential code, and the runtime switches between tasks when they perform asynchronous I/O, sleep, wait, or explicitly yield.
For example, this is perfectly ordinary-looking D:
void handleClient()
{
auto request = receiveRequest(); // May yield
auto data = loadData(request); // May yield
auto response = process(data);
sendResponse(response); // May yield
}The call stack remains intact while the task is suspended. You don't have to turn the function into a state machine or propagate futures through every layer.
However, there is one important distinction:
| Property | Go goroutines | Vibe.d tasks |
|---|---|---|
| Stackful | Yes | Yes |
| Lightweight tasks | Yes | Yes |
| Ordinary sequential code | Yes | Yes |
| Asynchronous networking | Runtime-managed | Event-loop-managed |
| Cooperative yielding | Supported | Yes |
| Preemptive scheduling | Yes, at safe points | No |
| Task interruption | Context/cancellation patterns | Task.interrupt() |
| Task groups | Library patterns | TaskGroup |
| Worker threads | Runtime-managed | Worker pool |
Go introduced asynchronous goroutine preemption in Go 1.14. Its runtime can interrupt a running goroutine at suitable safe points, rather than requiring it to voluntarily yield. Vibe.d does not do this. go.dev
Vibe.d is much closer to Lua's cooperative coroutine model than Go's scheduler. The difference is that Vibe integrates those coroutines with an asynchronous networking runtime and makes ordinary blocking-looking I/O operations yield automatically.
That's a perfectly reasonable model for web applications, provided you understand its limitations.
I'll use the modern, split-package version of Vibe.d rather than the older monolithic setup.
The relevant dependencies are:
dependency "vibe-core" version="~>2.15.0"
dependency "vibe-http" version="~>1.5.1"
dependency "d2sqlite3"
These are real, maintained components. vibe-core 2.15.0 was released in October 2026, while vibe-http 1.5.1 was released in April 2026. GitHub
For SQLite, I'll use D2SQLite3, a thin wrapper around the SQLite C API. It provides reference-counted Database and Statement structs, rather than making you deal with raw SQLite handles. dlang-community.github.io
This preserves your original application's structure, but adds three things worth examining:
- Individual request timeouts.
- Trackable and interruptible request tasks.
- Actual graceful shutdown with a bounded draining period.
The configuration, migration, and routing functions below represent the corresponding modules from your Go application, ported to D.
module app;
import core.exception : InterruptException;
import core.stdc.signal : SIGINT, SIGTERM, sig_atomic_t, signal;
import core.time : MonoTime, msecs, seconds;
import d2sqlite3 : Database;
import vibe.core.core : TaskGroup,
disableDefaultSignalHandlers,
exitEventLoop,
runApplication,
runTask,
setTimer,
sleep;
import vibe.core.task : Task;
import vibe.core.log : logInfo, logWarn, logError;
import vibe.http.server :
HTTPServerRequest,
HTTPServerResponse,
HTTPServerSettings,
listenHTTP;
import std.stdio : stderr, writeln;
// Your project-specific D modules:
import schatzhauser.config : Config, loadConfig;
import schatzhauser.db : runMigrations;
import schatzhauser.server : dispatchRoutes;
// ---------------------------------------------------------
// Signal handling
// ---------------------------------------------------------
__gshared sig_atomic_t caughtSignal;
extern(C) nothrow @nogc void onSignal(int sig)
{
// Do absolutely minimal work inside an OS signal handler.
volatile {
caughtSignal = cast(sig_atomic_t)sig;
}
}
sig_atomic_t readSignal() nothrow
{
sig_atomic_t result;
volatile {
result = caughtSignal;
}
return result;
}
void installSignalHandlers()
{
// Prevent Vibe from installing its default handlers, which
// terminate the event loop immediately.
disableDefaultSignalHandlers();
signal(SIGINT, &onSignal);
signal(SIGTERM, &onSignal);
}
// ---------------------------------------------------------
// Application state
// ---------------------------------------------------------
class App
{
Config cfg;
Database db;
bool stopping;
size_t inFlight;
// Handles for tasks that are currently processing requests.
TaskGroup requests;
// Background services, timers, scheduled jobs, etc.
TaskGroup background;
}
// ---------------------------------------------------------
// HTTP request handling
// ---------------------------------------------------------
void handleRequest(
App app,
scope HTTPServerRequest req,
scope HTTPServerResponse res
) nothrow
{
auto task = Task.getThis();
app.requests.add(task);
++app.inFlight;
// Interrupt this particular request after 15 seconds.
auto deadline = setTimer(15.seconds, () nothrow {
task.interrupt();
});
scope(exit) {
deadline.stop();
--app.inFlight;
}
try {
// Your existing route dispatch implementation.
// It has access to app.db and app.cfg.
dispatchRoutes(req, res, app.db, app.cfg);
} catch (InterruptException) {
// Request timed out or was cancelled during shutdown.
logWarn("request interrupted");
} catch (Exception e) {
logError("request failed: %s", e.msg);
try {
res.statusCode = 500;
res.writeBody("Internal Server Error");
} catch (Exception) {
// The connection may already be gone.
}
}
}
// ---------------------------------------------------------
// Application lifecycle
// ---------------------------------------------------------
int run()
{
// Configuration
Config cfg;
try {
cfg = loadConfig("config.toml");
} catch (Exception e) {
logError("failed to load config: %s", e.msg);
return 1;
}
logInfo("starting schatzhauser, debug=%s", cfg.debug);
auto app = new App;
app.cfg = cfg;
// -----------------------------------------------------
// Database
// -----------------------------------------------------
try {
app.db = Database(cfg.dbPath);
app.db.run("PRAGMA foreign_keys = ON;");
// Equivalent to a basic PingContext sanity check.
app.db.execute("SELECT 1").oneValue!int;
runMigrations(app.db);
} catch (Exception e) {
logError("database initialization failed: %s", e.msg);
return 1;
}
// -----------------------------------------------------
// HTTP server
// -----------------------------------------------------
installSignalHandlers();
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.keepAliveTimeout = 30.seconds;
settings.maxRequestSize = 2 * 1024 * 1024;
auto listener = listenHTTP(
settings,
(scope HTTPServerRequest req,
scope HTTPServerResponse res) nothrow
{
handleRequest(app, req, res);
}
);
scope(exit) listener.stopListening();
logInfo("listening on :8080");
// -----------------------------------------------------
// Example background service
// -----------------------------------------------------
app.background.run(() nothrow {
try {
while (true) {
// Perform periodic background work.
sleep(30.seconds);
}
} catch (InterruptException) {
logInfo("background service stopped");
}
});
// -----------------------------------------------------
// Shutdown monitor
// -----------------------------------------------------
runTask(() nothrow {
try {
// Wait for SIGINT or SIGTERM.
while (readSignal() == 0) {
sleep(50.msecs);
}
logInfo("shutdown signal received: %s", readSignal());
app.stopping = true;
// 1. Stop accepting new connections.
listener.stopListening();
// 2. Give existing requests up to five seconds.
auto deadline = MonoTime.currTime + 5.seconds;
while (
app.inFlight != 0 &&
MonoTime.currTime < deadline
) {
sleep(10.msecs);
}
// 3. If necessary, request cancellation.
if (app.inFlight != 0) {
logWarn(
"drain deadline exceeded; interrupting requests"
);
app.requests.interrupt();
auto cancelDeadline =
MonoTime.currTime + 1.seconds;
while (
app.inFlight != 0 &&
MonoTime.currTime < cancelDeadline
) {
sleep(10.msecs);
}
}
// 4. We cannot safely close a shared DB connection
// while request handlers are still using it.
if (app.inFlight != 0) {
logError(
"requests failed to terminate; forcing shutdown"
);
exitEventLoop();
return;
}
// 5. All request tasks have finished.
app.requests.join();
// 6. Cancel background services and wait for them.
app.background.interrupt();
app.background.join();
logInfo("shutdown complete");
// Exit the event loop. Main will close the database.
exitEventLoop();
} catch (Exception e) {
logError("shutdown failed: %s", e.msg);
exitEventLoop();
}
});
// -----------------------------------------------------
// Run event loop
// -----------------------------------------------------
const result = runApplication();
// All normal request processing has stopped.
app.db.close();
return result;
}
// ---------------------------------------------------------
// Entry point
// ---------------------------------------------------------
int main()
{
try {
return run();
} catch (Exception e) {
stderr.writeln(e.msg);
return 1;
}
}This is an API-level implementation rather than a compiler-verified drop-in project. In particular, Config, loadConfig, runMigrations, and dispatchRoutes are your application-specific D modules, and their signatures need to match the code above.
There are some important design decisions here.
There isn't a direct equivalent of Go's context.Context in this Vibe.d model.
Instead, there are three mechanisms:
1. Individual task interruption
auto task = Task.getThis();
// Somewhere else:
task.interrupt();Vibe delivers an InterruptException when the task next reaches an interruptible operation.
2. Timeouts
auto timer = setTimer(5.seconds, () nothrow {
task.interrupt();
});
scope(exit) timer.stop();This is particularly nice. You can apply deadlines to ordinary sequential functions without changing all their signatures.
3. Task groups
TaskGroup jobs;
jobs.run(() nothrow {
try {
while (true) {
doWork();
sleep(1.seconds);
}
} catch (InterruptException) {
logInfo("worker stopped");
}
});
// Shutdown:
jobs.interrupt();
jobs.join();This is quite a pleasant API. Vibe-core introduced TaskGroup in version 2.12 specifically to manage task lifetimes. GitHub
There is one catch, though.
Interruption is cooperative. It isn't equivalent to forcibly terminating a goroutine.
For example:
void infiniteLoop()
{
while (true) {
calculateSomething();
}
}If this runs inside a Vibe task, another task cannot interrupt it at an arbitrary instruction.
You need an explicit checkpoint:
void infiniteLoop()
{
while (true) {
calculateSomething();
yield();
}
}Or use asynchronous operations that naturally yield.
The same applies to timers. Vibe's documentation explicitly describes its timers as non-preemptive. They cannot execute while another task monopolizes the event-loop thread. GitHub
That is the single biggest difference from Go.
This is where the comparison gets interesting. The code looks quite reasonable, but several differences become apparent when you examine the APIs more closely.
Go has a universal cancellation mechanism that libraries can accept:
func LoadUser(ctx context.Context, id int) (*User, error)A function can propagate cancellation to everything it calls.
Vibe has Task.interrupt(), which is convenient but tied to individual tasks. It throws an exception at an interruptible operation.
This has consequences:
- You need access to the task handle to interrupt it.
- Libraries must cooperate with interruption.
- You have to decide which exceptions represent cancellation.
- There is no equivalent universal cancellation tree.
TaskGroup helps considerably, but it doesn't replace the flexibility of passing a cancellation context through your application.
My preference would be to use task interruption for ordinary service lifetimes and introduce an explicit cancellation token only where independent parts of the application need to share cancellation state.
Your Go example has:
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,Vibe's HTTPServerSettings has:
keepAliveTimeoutmaxRequestSizemaxRequestHeaderSizemaxRequestTime
Unfortunately, maxRequestTime is explicitly documented as not implemented yet.
There are no direct equivalents of Go's ReadTimeout and WriteTimeout in these settings. vibe-http.dpldocs.info
The per-request timer in my implementation is an application-level workaround. It starts when your handler runs, not when the server begins reading the request.
It also cannot interrupt a handler that never yields.
This is a genuine maturity gap, not just a difference in syntax.
Go gives you:
srv.Shutdown(ctx)That handles stopping the listener and waiting for active connections to finish.
Vibe provides:
listener.stopListening();This stops listening, but it doesn't give you the same convenient, context-aware server shutdown operation. You need to track active requests and implement draining yourself. vibe-http.dpldocs.info
Notice something else in my implementation: the signal handler doesn't perform application shutdown. It merely records the signal. A regular Vibe task observes it and performs cleanup.
This avoids trying to run ordinary application code inside an operating-system signal handler.
It's a reasonable solution, but more machinery than Go.
This is particularly relevant to your example.
D2SQLite3 wraps the SQLite C API. Its database operations are synchronous. dlang-community.github.io
Suppose a request does this:
auto results = app.db.execute("SELECT ...");That operation runs on the event-loop thread.
If it takes 200 ms, other tasks on that event loop cannot execute during those 200 ms.
Go doesn't have exactly the same problem because its runtime can schedule other goroutines when a goroutine blocks in a system call or enters a blocking C call, using additional OS threads where necessary. go.dev
With Vibe, you have a few options:
- Accept synchronous SQLite operations when they are short.
- Execute potentially blocking operations using Vibe's worker-task facilities, with appropriately isolated database connections.
- Use a database driver designed around Vibe's asynchronous I/O model.
For a small SQLite application, option one might be perfectly adequate. But it is important to understand that stackful fibers don't automatically make every synchronous operation non-blocking.
Something I particularly like about D is that you aren't limited to Vibe.
There are essentially three approaches available.
| Approach | Programming model | Scheduling |
|---|---|---|
core.thread.Fiber |
Stackful coroutines | Cooperative |
std.concurrency |
Message-passing threads/actors | Kernel threads by default; alternative schedulers |
| Vibe-core | Stackful asynchronous tasks | Cooperative fibers + event loop |
D's std.concurrency is interesting.
It has:
import std.concurrency;
auto worker = spawn(&workerFunction);
send(worker, 42);
auto result = receiveOnly!int();It also supports different schedulers, including FiberScheduler.
By default, spawn creates a kernel thread. You can instead select a scheduler that multiplexes fibers. The standard library explicitly describes these as alternative implementations of its logical-thread abstraction. dlang.org
This is actually quite elegant conceptually.
You can use a message-passing architecture without committing to an operating-system thread per actor.
However, D doesn't magically provide Go's scheduler when you switch to FiberScheduler. You are still dealing with cooperative scheduling.
One more Vibe detail worth knowing: runTask begins executing the new task synchronously until it reaches its first yield or asynchronous operation. It isn't necessarily deferred until some later scheduler iteration. GitHub
That can be useful for predictability, but it differs from Go's go statement.
I would separate three questions.
D offers a substantially richer language.
You get:
- Templates and powerful compile-time programming.
- UFCS and ranges.
- Mixins and compile-time reflection.
- Structs with deterministic destruction.
scope(exit),scope(success)andscope(failure).- Both GC-managed and manually managed memory.
- Native interoperability with C.
@safe,pure,nothrowand other useful restrictions.
You can write fairly high-level code without surrendering the ability to control memory and native operations.
I think this is probably D's strongest argument against Go.
Go intentionally limits its expressive power. D doesn't have that philosophy.
D compiles to native code, and LDC's LLVM backend provides an excellent optimizing compiler.
There is no fundamental reason D couldn't outperform Go in a particular application.
However, I wouldn't expect Vibe.d automatically to outperform Go's HTTP server.
The event loop, database access, memory allocation, garbage collection and actual workload matter considerably more than language-level expressiveness.
In particular, cooperative scheduling can be an advantage when operations are genuinely asynchronous, but a disadvantage when you have unpredictable blocking operations.
This is the part where I wouldn't be so enthusiastic about replacing Go.
D has more language features, but that doesn't necessarily mean fewer warts.
You now have to understand the interactions between:
- GC and deterministic destruction.
- References, ownership and lifetimes.
sharedand thread safety.@safeand@system.- Exception handling and
nothrow. - Compiler differences and library compatibility.
Even the Vibe example illustrates this: callbacks passed to runTask must be nothrow, meaning exceptions need to be handled inside the callback rather than simply escaping. GitHub
Go has its own annoyances, but its runtime, concurrency model and standard library are unusually cohesive.
D provides more freedom, but you have to do more engineering yourself.
I think D is worth exploring, especially because you aren't insisting on Go's exact preemptive scheduling model.
There is a distinction between two goals:
Goal A: Go, but more expressive and faster.
D doesn't achieve this completely. In particular, Vibe's cooperative scheduler is a fundamental difference, not a small implementation detail.
Goal B: A productive native language with stackful coroutines, asynchronous I/O, good metaprogramming and an enjoyable programming experience.
D is a much stronger candidate here.
I'd give Vibe.d particular credit for trying to solve the problem properly. It isn't some experimental coroutine wrapper. It has a real event loop, networking, task management, timers, synchronization, worker threads and logging. Its core and HTTP packages are still receiving releases in 2026. GitHub
I would actually experiment with D in two stages.
Stage 1: Vibe.d
Build an ordinary web application using:
- Vibe HTTP server.
- Vibe tasks.
- TaskGroup.
- Interruptible operations.
- Timers.
- SQLite or PostgreSQL.
See whether the cooperative execution model feels natural. Pay particular attention to blocking database operations and cancellation.
Stage 2: D without Vibe
Try building a small application around std.concurrency, FiberScheduler and perhaps your own lightweight event loop.
This would tell you whether you prefer Vibe's integrated runtime or D's lower-level building blocks.
I wouldn't immediately start writing a replacement for Go's scheduler. There is a lot of value in a cooperative runtime when you embrace its model.
| Category | My assessment |
|---|---|
| Language expressiveness | Excellent |
| Native performance potential | Excellent |
| Stackful coroutines | Excellent |
| Go-like preemption | Missing in Vibe |
| Cancellation | Good primitives, more manual integration |
| Async networking | Mature |
| Structured task lifetimes | Good |
| HTTP server functionality | Good, some timeout gaps |
| Overall productivity potential | High |
I wouldn't call D a better Go. I'd call it a potentially more enjoyable systems programming language that can provide a very productive Go-like development experience, provided you're comfortable with cooperative concurrency.
And that's not a small qualification, but given that Lua-style coroutines are acceptable to you, I think it makes D a genuinely interesting candidate.
One thing I'd particularly investigate next is D + Vibe's cooperative tasks versus D's std.concurrency with FiberScheduler. That comparison gets closer to your actual architectural preferences than comparing D and Go's syntax or benchmark results.
-
How to do per‑request deadline propagation, to cancel downstream work when request dies?
-
How to tell handlers "give up", i.e. cancellation token / context? No Context tree with deadline inheritance; deadlines are per‑timer, not propagated?
-
stopListening() is graceful but does not force‑kill after a deadline?
-
At the web app coder/user level where would I need core.thread.Fiber with yield() if this is already abstracted away by vibe-core (Task)?
-
Does the need to write your own scheduler arise often? Is raw core.thread.Fiber mostly for custom runtimes?
-
std.parallelism is for CPU bound parallelism with OS threads and std.concurrency is for actor style messaging/channels between OS threads? Is this largely avoidable or concurrency gets mixed with parallelism in D in intricate ways, any footguns at the ordinary web app level? Confused with vibe.d event-loop tasks, worker tasks and possibly ordinary D threads. How compatible is D stdlib with vibe.d? Why is vibe.d not in stdlib?
-
When is forgetting to yield actually a problem? How do I see what function yields? Is this the best or the worst case between seamless preemptive goroutines and explicit friction prone async/await?
Your questions expose the most important weakness in Vibe.d: it gives you stackful, sequential-looking concurrency, but it doesn't give you Go's integrated cancellation and scheduling model.
There is good news, though. You don't need to implement an entire concurrency framework to address most of this. Vibe already provides some useful building blocks. The trick is understanding exactly what they do and where they stop.
I'll go through the six areas, then give you my overall assessment.
First, an important distinction.
Consider this call chain:
void handleRequest()
{
auto user = loadUser(42);
auto orders = loadOrders(user.id);
auto result = generateResponse(user, orders);
}Suppose handleRequest() is running inside a Vibe task.
All these function calls execute on the same task and share the same fiber stack.
Consequently, if somebody calls:
Task.getThis().interrupt();on the request task, the interruption will be delivered when that task next reaches an interruptible Vibe operation.
This means that ordinary function calls don't need cancellation propagation at all.
For example:
User loadUser(int id)
{
auto connection = connectToDatabase();
return connection.queryUser(id);
}If the underlying operations use Vibe's interruptible APIs, they participate in the same task interruption.
That's a substantial simplification compared with Go's requirement to pass context.Context through every layer.
However, there are two cases where this stops being sufficient:
- You create additional tasks.
- You execute work on another thread, particularly CPU-intensive or blocking work.
Those require additional coordination.
I'd implement a small request-scoped object with three responsibilities:
- An absolute deadline.
- A cancellation state/reason.
- A group of child tasks.
Conceptually:
class RequestScope
{
Task owner;
TaskGroup children;
MonoTime deadline;
bool cancelled;
void cancel()
{
cancelled = true;
// Interrupt independent child tasks.
children.interrupt();
// Interrupt the original request task.
owner.interrupt();
}
void checkCancelled()
{
if (cancelled || MonoTime.currTime >= deadline)
throw new RequestCancelledException();
}
}This is illustrative rather than a complete implementation. In particular, cross-thread access to the cancellation state needs synchronization.
The request handler creates the scope:
auto scope = new RequestScope;
scope.owner = Task.getThis();
scope.deadline = MonoTime.currTime + 15.seconds;Then it installs a deadline timer:
auto timer = setTimer(15.seconds, () nothrow {
scope.cancel();
});
scope(exit) timer.stop();Child tasks are registered with the request:
TaskGroup children;
children.run(() nothrow {
try {
performIndependentWork();
} catch (InterruptException) {
// Child task cancelled.
} catch (Exception e) {
logError("child task failed: %s", e.msg);
}
});The scope owns the child group, and cancellation interrupts both the request task and its children.
At the end, the application joins outstanding children. Remember that TaskGroup's destructor joins tasks but does not automatically interrupt them.
Vibe's actual TaskGroup API provides:
group.run(...);
group.runInWorker(...);
group.add(task);
group.interrupt();
group.join();
group.joinUninterruptible();It was introduced in vibe-core 2.12.0. It is a lifetime-management primitive, not a complete cancellation context. GitHub
This is something you'd implement yourself.
Use absolute monotonic deadlines rather than repeatedly starting independent relative timers.
Suppose the incoming request has 15 seconds remaining:
Request deadline: 15 seconds
|
+-- Database operation: maximum 5 seconds
|
+-- HTTP service: maximum 8 seconds
|
+-- Response generation: remaining request budget
Every child operation calculates:
effective deadline = min(parent deadline, local deadline)
In other words, a downstream operation can shorten its parent's deadline but cannot extend it.
This also gives you a useful remaining() function for APIs that accept explicit timeouts.
There is one subtlety: Vibe's Task.interrupt() doesn't carry a cancellation reason. It simply requests interruption. Your scope should retain the reason, such as:
- Request deadline exceeded.
- Client disconnected.
- Server shutting down.
- Parent operation cancelled.
Then your handler can distinguish these cases.
My conclusion: You can get a reasonable approximation of Go's cancellation tree with a small RequestScope abstraction. But it is your abstraction, not something provided by Vibe.
There are actually two different mechanisms.
For ordinary Vibe tasks:
task.interrupt();The target task receives an InterruptException when it reaches an interruptible operation.
You catch it at the appropriate boundary:
try {
processRequest();
} catch (InterruptException) {
logInfo("request cancelled");
return;
}This is nice because intermediate functions don't need to return special error values.
It resembles throwing an exception through an ordinary call stack, which is exactly what happens.
The official implementation confirms that interruption is deferred until the task calls an interruptible function. Vibe Core Documentation
For work that doesn't necessarily execute as a Vibe task, you need an explicit token.
For example:
void expensiveCalculation(RequestScope scope)
{
foreach (i; 0 .. 10_000_000) {
scope.checkCancelled();
calculateSomething(i);
}
}This matters for CPU-heavy operations and worker-thread functions.
A worker doing a long calculation isn't going to magically stop because its parent request received an interruption.
You can also use this mechanism for libraries that don't understand Vibe's task interruption.
One important detail: interruption is not an unconditional exception injected into arbitrary code. It happens at supported suspension/interruption points. A function doing a long computation or sitting inside a blocking C library call might not observe it.
That's the fundamental limitation.
No.
And this is a fairly significant difference from Go's http.Server.Shutdown.
Vibe:
listener.stopListening();Stops accepting new connections and closes the listening port if possible.
It doesn't:
- Interrupt existing request handlers.
- Cancel their child tasks.
- Wait for requests to finish.
- Enforce a shutdown deadline.
- Forcefully terminate running handlers.
That's explicitly the documented scope of HTTPListener.stopListening(). vibe-http.dpldocs.info
You need to implement draining yourself.
I'd use this sequence:
| Stage | Action |
|---|---|
| 1 | Stop accepting connections |
| 2 | Mark application as shutting down |
| 3 | Wait up to five seconds for active requests |
| 4 | Interrupt remaining request tasks |
| 5 | Wait another second for cleanup |
| 6 | Close database and other resources |
| 7 | Exit |
But there's an important distinction between interruption and forced termination.
Vibe cannot safely kill an arbitrary fiber in the middle of executing application code.
Imagine a task doing:
db.beginTransaction();
modifySomeData();
updateSomeOtherData();
db.commit();Killing it between these operations could leave resources and transactions in an undesirable state.
Vibe's approach is to request interruption and let the task unwind normally.
If a task refuses to yield or is trapped inside an uninterruptible operation, you cannot safely force it to terminate individually.
For a genuinely hard process shutdown deadline, use the process supervisor as the final enforcement mechanism.
Also, don't close the shared database while outstanding tasks might still be using it.
exitEventLoop() is an event-loop termination mechanism, not a safe individual-task kill operation. GitHub
Verdict: Vibe provides the primitives for graceful draining, but not Go's ready-made HTTP shutdown orchestration.
You generally wouldn't.
This is an important distinction:
core.thread.Fiberis D's low-level stackful coroutine implementation.
Vibe builds its own task abstraction on top of fibers.
At application level, you use:
runTask(...);and:
Task.getThis();And when you want to yield to Vibe's scheduler:
import vibe.core.core : yield;
yield();You don't manually create fibers or manage their stacks.
Think of it this way:
| Layer | Responsibility |
|---|---|
core.thread.Fiber |
Low-level coroutine implementation |
Vibe Task |
Managed asynchronous execution |
| Vibe scheduler | Schedules tasks |
| Vibe event driver | Handles asynchronous I/O |
| Your application | Creates tasks and implements business logic |
You should almost never touch core.thread.Fiber when writing an ordinary Vibe application.
The same applies to implementing your own scheduler. That's runtime/library development, not normal application development.
For ordinary applications: no.
Vibe already provides the scheduler and event loop.
You have several options for executing work:
runTask(() nothrow {
try {
handleSomething();
} catch (Exception e) {
logError("%s", e.msg);
}
});This creates another task on the Vibe event-loop thread.
It is cooperative, not CPU-parallel.
runWorkerTask(&performCpuWork, input);This executes work on a worker thread.
Useful for:
- CPU-intensive computations.
- Blocking operations.
- Synchronous libraries that would otherwise block the event loop.
The corresponding TaskGroup.runInWorker() also allows you to manage worker task lifetimes.
There are thread-safety restrictions: worker functions and their arguments must satisfy Vibe's weak-isolation requirements. This is intentional.
There is also:
import vibe.core.concurrency : async;This is particularly interesting.
Vibe's async chooses the execution mechanism based on argument isolation:
- Weakly isolated callable and arguments: worker thread.
- Otherwise: ordinary Vibe task on the calling thread.
It returns a Future.
This automatic choice is convenient, but also something to understand because async doesn't necessarily mean running on a separate thread. Vibe Core Documentation
Only if I wanted something fundamentally different from Vibe:
- An actor runtime with custom scheduling.
- A specialized simulation runtime.
- A custom coroutine implementation.
- A different event-loop architecture.
- A scheduler with particular real-time or workload characteristics.
For your web application, this is unnecessary engineering.
This is probably the most confusing part of D concurrency because D offers several overlapping abstractions.
Let's separate them.
| Facility | Primary purpose | Execution |
|---|---|---|
Vibe runTask |
Asynchronous application tasks | Fibers on event-loop thread |
Vibe runWorkerTask |
Blocking/CPU work | Worker OS threads |
std.parallelism |
Parallel computation | OS thread pool |
std.concurrency |
Message passing | OS threads by default |
There is also core.thread.Thread, which gives you direct access to operating-system threads.
This is essentially D's CPU-parallelism toolkit.
For example:
import std.parallelism;
foreach (item; parallel(items)) {
process(item);
}The iterations execute across worker threads.
It also provides parallel map/reduce operations and futures.
Its intended purpose is parallel execution of independent computations, not asynchronous application I/O. dlang.org
This is a low-level message-passing API.
For example:
import std.concurrency;
auto worker = spawn(&workerFunction);
send(worker, 42);
auto value = receiveOnly!int();The interesting detail is its scheduler abstraction.
By default, spawn creates an OS thread. But you can substitute FiberScheduler, which multiplexes logical threads using fibers.
This is quite an interesting design, actually.
However, that FiberScheduler is not Vibe's scheduler. It doesn't automatically integrate with Vibe's event loop or asynchronous network operations.
I wouldn't use it inside an ordinary Vibe application. dlang.org
I'd establish a simple rule:
Use Vibe for application concurrency. Use Vibe worker tasks for work that must leave the event loop.
Don't introduce std.parallelism or std.concurrency unless you have an actual requirement for their particular functionality.
In particular, avoid accidentally creating several independent thread pools. Vibe already has its own worker pool.
Yes, in the normal language/library sense.
You can freely use:
std.algorithmstd.rangestd.arraystd.stringstd.jsonstd.formatstd.datetime- Other ordinary Phobos functionality.
Vibe is built to work with the D language and standard library.
But there is an important distinction:
Compatible does not mean asynchronous.
For example:
import std.file;
auto contents = read("large-file.dat");That's ordinary synchronous file I/O.
It can block the event-loop thread.
Compare it with:
import vibe.core.file;
auto contents = readFile("large-file.dat");Vibe provides asynchronous file operations, internally using worker tasks where necessary.
This distinction is explicitly discussed in Vibe's documentation. GitHub
Because D's standard library, Phobos, provides general language-level functionality.
An asynchronous networking runtime and web framework are much more opinionated. They involve platform-specific event drivers, networking, scheduling, HTTP, TLS and other external dependencies.
Vibe is a community framework rather than an official component of Phobos.
I wouldn't interpret that as a fundamental architectural limitation of D.
It's mainly an ecosystem and standard-library governance decision.
This is the most interesting question, and perhaps the most important for evaluating Vibe.
Let's establish what happens.
Suppose you have 100 concurrent HTTP requests.
Each request is a separate Vibe task.
They all share an event-loop thread.
Imagine this handler:
void handler()
{
auto user = loadUser();
auto result = calculateSomething();
sendResponse(result);
}loadUser() might perform asynchronous database/network operations.
During those operations, the task suspends and the event loop processes other tasks.
That's automatic.
You don't need to manually write:
yield();after every operation.
But consider:
void calculateSomething()
{
double result = 0;
foreach (i; 0 .. 100_000_000) {
result += expensiveCalculation(i);
}
}This is a synchronous CPU-intensive function.
Nothing gives control back to the event loop.
Other requests stop progressing.
Timers don't fire.
Other tasks don't execute.
The entire event loop is effectively monopolized.
The solution is either to move this work to a worker thread or periodically yield:
void calculateSomething()
{
double result = 0;
foreach (i; 0 .. 100_000_000) {
result += expensiveCalculation(i);
if (i % 10_000 == 0)
yield();
}
}Vibe explicitly recommends periodic yielding for long-running CPU computations. Its yield() is interruptible and can throw InterruptException. Vibe Core Documentation
In a normal I/O-heavy web application, probably not.
Consider the following:
| Operation | Usually yields? |
|---|---|
| Vibe TCP read/write | Yes |
| Vibe HTTP request | Yes, at its asynchronous operations |
| Vibe sleep | Yes |
| Vibe task synchronization | Yes |
| Vibe asynchronous file operations | Yes |
std.file.read |
No |
| SQLite synchronous query | No |
| Large CPU calculation | No |
| Ordinary arithmetic | No |
You don't need to pepper your entire application with yield().
You only need to worry about code that monopolizes the event-loop thread.
Unfortunately, this is one of Vibe's disadvantages.
There is no compiler-enforced distinction between:
void loadData();and:
void calculateData();One might perform asynchronous I/O and suspend. The other might run synchronously for several seconds.
Both have ordinary D function signatures.
You have to understand the implementation or documentation of the functions you're calling.
This is very different from explicit async/await, where the suspension points are visible in the syntax and propagate through the call graph.
You can also use Vibe's task-event debugging hooks to observe task scheduling, but they don't provide a static guarantee that a function won't block. GitHub
I think you've identified a genuine architectural trade-off.
There are three different approaches:
| Property | Go goroutines | Vibe.d | Async/await |
|---|---|---|---|
| Stackful | Yes | Yes | Usually no |
| Sequential syntax | Yes | Yes | Partially |
| Automatic I/O suspension | Yes | Yes | Explicit await |
| Preemptive CPU scheduling | Yes | No | Usually no |
| Manual yielding for CPU work | Generally unnecessary | Sometimes | Usually unnecessary for fairness between awaits |
| Explicit suspension points | No | No | Yes |
| Cancellation propagation | Context | Custom scope/task interruption | Usually explicit token/task cancellation |
| Blocking third-party libraries | Better runtime integration | Potential event-loop blockage | Depends on executor |
The most interesting thing about Vibe is that it isn't really an async/await implementation.
It is closer to implicit async/await using stackful coroutines.
That has advantages.
You can write:
auto user = loadUser(id);
auto orders = loadOrders(user.id);
auto result = calculate(user, orders);There is no asynchronous function coloring.
The suspension happens inside the I/O functions, not in the syntax of every caller.
But there's a price.
The hidden suspension problem
Imagine:
void updateAccount(Account account)
{
account.balance -= 100;
saveAccount(account); // Potential suspension.
account.lastTransaction = currentTransaction;
}If saveAccount() yields, another task might execute before this function continues.
That other task might access the same account.
You now have a logical interleaving point that isn't obvious from the caller's source code.
You don't necessarily have a conventional multithreaded data race, because both tasks may be running on the same OS thread. But you can certainly have inconsistent application state.
This is one reason explicit async/await can be attractive: suspension points are visible.
Conversely, Go hides suspension too, but its runtime provides preemptive scheduling and handles blocking syscalls much more comprehensively.
Vibe gives you some of Go's syntax simplicity without all of Go's scheduling guarantees.
That's the key distinction.
I would not dismiss D or Vibe based on these limitations.
In fact, I think Vibe has an appealing programming model for someone who enjoys sequential code and stackful coroutines.
But I would establish a few architectural rules:
| Rule | Reason |
|---|---|
| One Vibe task per logical request | Simple execution model |
| Direct calls share request interruption | No context propagation through ordinary calls |
| One request-scoped TaskGroup | Manage independent child tasks |
| One absolute request deadline | Prevent downstream operations extending request lifetime |
| Worker tasks for blocking operations | Keep event loop responsive |
| Explicit cancellation checks in CPU/worker code | Cooperative cancellation |
| Avoid additional concurrency frameworks | Prevent scheduler and thread-pool complexity |
I particularly like the fact that you can get away with a fairly small architecture.
You don't need actors, a global message bus, elaborate scheduling policies or an application-wide concurrency framework.
But I'd be honest about the weaknesses:
Go is substantially better at making concurrency work without the programmer constantly thinking about scheduling.
D is more expressive, and Vibe offers a pleasant coroutine experience, but the programmer assumes more responsibility for cancellation, blocking operations and task lifetimes.
One final observation: I wouldn't try to recreate Go's context.Context in its entirety. I'd implement a small RequestScope containing an absolute deadline, cancellation reason and child-task group. That solves most of the practical problems without importing Go's entire cancellation philosophy into D.
For your intended kind of programming, that's probably the sweet spot.
I will not ask you to code a concurrent system in Haskell, I am not a cruel man.
😂 Much appreciated. I was already preparing a ReaderT Env (ExceptT Error (ResourceT IO)) with structured cancellation, STM channels, and a PhD thesis on why nothing happens until you execute the program.
Let's keep the web server boring. Life is complicated enough.
