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

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
雷峰网
雷峰网
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
WordPress大学
WordPress大学
小众软件
小众软件
P
Proofpoint News Feed
IT之家
IT之家
Apple Machine Learning Research
Apple Machine Learning Research
T
The Exploit Database - CXSecurity.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threat Research - Cisco Blogs
K
Kaspersky official blog
V
V2EX
博客园 - Franky
Cisco Talos Blog
Cisco Talos Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Scott Helme
Scott Helme
量子位
SecWiki News
SecWiki News
博客园 - 叶小钗
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Attack and Defense Labs
Attack and Defense Labs
T
Tailwind CSS Blog
Google DeepMind News
Google DeepMind News
T
Tor Project blog
N
News and Events Feed by Topic
The Cloudflare Blog
Help Net Security
Help Net Security
Forbes - Security
Forbes - Security
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
P
Privacy & Cybersecurity Law Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
A
Arctic Wolf
L
LangChain Blog
Latest news
Latest news
S
Schneier on Security
C
CERT Recently Published Vulnerability Notes
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园_首页
T
The Blog of Author Tim Ferriss
Schneier on Security
Schneier on Security
S
Security @ Cisco Blogs
Hugging Face - Blog
Hugging Face - Blog
MyScale Blog
MyScale Blog
Blog — PlanetScale
Blog — PlanetScale
O
OpenAI News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Async Transactions for Signals: Batching Updates Across await
Luciano0322 · 2026-04-27 · via DEV Community

Introduction

In the previous articles, we demonstrated how to integrate our signal mechanism into two mainstream frameworks: React and Vue.

Starting from this article, we will return to the core signal kernel we designed and examine which parts can be improved further.

Quick Overview

The goal is to merge “multi-step updates across await boundaries” into a single effect rerun, while keeping our existing lazy computed behavior and microtask-based scheduling model intact.

In this article, we only extend scheduler.ts and a few minimal integration points, without changing the public API.

Why Do We Need Async Transactions?

Our current system is already stable:

Within the same call stack, multiple set() calls are merged by our scheduler — using Set + queueMicrotask — into the same microtask, so the effect only reruns once.

But this does not work across await.

Each await creates a new microtask. Without a transaction, effects will run once per async boundary.

Without vs. With Transaction

// ❌ Without transaction: the effect runs twice
async function onClick() {
  a.set(1); // schedules the first flush
  await fetch("/api");
  b.set(2); // schedules the second flush
}

// ✅ With transaction: the effect runs once after the transaction completes
async function onClick() {
  await transaction(async () => {
    a.set(1);
    await fetch("/api");
    b.set(2);
  });
}

Enter fullscreen mode Exit fullscreen mode

Minimal Change: Extending scheduler.ts

Core Idea

Reuse the existing batchDepth, so batch() and transaction() can be nested freely.

When batchDepth > 0, scheduleJob() only adds the job to the queue and does not schedule a microtask.

When the outermost transaction exits, we call flushJobs() once.

// scheduler.ts
export interface Schedulable { run(): void; disposed?: boolean }

const queue = new Set<Schedulable>();
let scheduled = false;
let batchDepth = 0;

export function scheduleJob(job: Schedulable) {
  if (job.disposed) return;
  queue.add(job);

  // Only schedule a microtask when we are not inside a batch/transaction
  if (!scheduled && batchDepth === 0) {
    scheduled = true;
    queueMicrotask(flushJobs);
  }
}

// Same as before: merge synchronous updates and flush once at the end
export function batch<T>(fn: () => T): T {
  batchDepth++;
  try {
    return fn();
  } finally {
    batchDepth--;
    if (batchDepth === 0) flushJobs();
  }
}

// Promise-like check
function isPromiseLike<T = unknown>(v: any): v is PromiseLike<T> {
  return v != null && typeof v.then === "function";
}

// New: async transaction support.
// Updates across await boundaries are merged and flushed once
// when the outermost transaction completes.
export function transaction<T>(fn: () => T): T;
export function transaction<T>(fn: () => Promise<T>): Promise<T>;
export function transaction<T>(fn: () => T | Promise<T>): T | Promise<T> {
  batchDepth++;

  try {
    const out = fn();

    if (isPromiseLike<T>(out)) {
      // Async case: wait until fn completes, then exit and flush if needed
      return Promise.resolve(out).finally(() => {
        batchDepth--;
        if (batchDepth === 0) flushJobs();
      });
    }

    // Sync case: exit immediately and flush if needed
    batchDepth--;
    if (batchDepth === 0) flushJobs();

    return out as T;
  } catch (e) {
    // Even when an exception is thrown, we must exit correctly and flush once
    batchDepth--;
    if (batchDepth === 0) flushJobs();
    throw e;
  }
}

export function flushSync() {
  if (!scheduled && queue.size === 0) return;
  flushJobs();
}

function flushJobs() {
  scheduled = false;

  let guard = 0;

  while (queue.size) {
    const list = Array.from(queue);
    queue.clear();

    for (const job of list) job.run();

    if (++guard > 10000) {
      throw new Error("Infinite update loop");
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

This is backward-compatible.

All existing batch() usage remains unchanged. After adding transaction(async), multiple set() calls across await boundaries can also be merged into a single effect rerun.

Existing code does not need to change:

  • signal.set() still calls effect.schedule().
  • EffectInstance.schedule() still calls scheduleJob(this).
  • computed remains lazy: it is only marked as stale and does not enter the scheduler.

Behavioral Guarantees

computed Is Still Lazy

set() only marks the computed node as stale.

It will not be recomputed early just because it is inside a transaction.

Effects Run Once After the Transaction Ends

Any set() inside the transaction does not schedule a microtask immediately.

Only when the outermost transaction exits do we call flushJobs() once.

Nesting Is Supported

Because batchDepth is shared, nested batch() and transaction() calls work naturally.

Only the outermost exit triggers the flush.

Exception-Safe

Even if fn throws, the scheduler exits the transaction state correctly and flushes once.

See the catch / finally logic above.

Usage Guide

Using It in React

Multi-Step Updates Across await

// Counter.tsx
import React from "react";
import { signal } from "../core/signal.js";
import { createEffect } from "../core/effect.js";
import { transaction } from "../core/scheduler.js";
import { useSignalValue } from "./react-adapter";

// Data layer, independent of React
const a = signal(0);
const b = signal(0);

// Observe effect reruns
createEffect(() => {
  // A single rerun sees the latest values of both a and b
  console.log("effect run:", a.get(), b.get());
});

export function Counter() {
  const va = useSignalValue(a);
  const vb = useSignalValue(b);

  const onClick = async () => {
    await transaction(async () => {
      a.set(va + 1);
      await Promise.resolve(); // Simulate an await, such as fetch()
      b.set(vb + 1);
    }); // Flush only after the transaction ends
  };

  return (
    <div>
      <p>a={va} / b={vb}</p>
      <button onClick={onClick}>
        +a, then await, then +b (one rerun)
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Local Draft + Commit Once on Submit

Usually, this does not require startTransition.

import { useEffect } from "react";
import { signal } from "../core/signal.js";
import { transaction } from "../core/scheduler.js";
import { useSignalValue, useSignalState } from "./react-adapter";

const titleSig = signal("Hello");

export function Editor() {
  const committed = useSignalValue(titleSig);
  const [draft, setDraft] = useSignalState(committed); // Local signal draft

  // Optional: sync the draft when the external value changes
  useEffect(() => setDraft(committed), [committed]);

  const save = async () => {
    await transaction(() => {
      titleSig.set(draft); // Commit back to the global signal once

      // If there are many React setState calls here,
      // then consider wrapping those setState calls with startTransition.
    });
  };

  return (
    <>
      <input value={draft} onChange={(e) => setDraft(e.target.value)} />
      <button onClick={save}>Save</button>
      <p>committed: {committed}</p>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

Reminder:
startTransition does not change the priority of signal.set().
It only affects React’s own setState.
For merging multi-step data updates, use transaction(async).
For UI transitions, use useDeferredValue or local draft state/signals.

Using It in Vue

Multi-Step Updates Across await in an SFC

<script setup lang="ts">
import { signal } from "../core/signal.js";
import { transaction } from "../core/scheduler.js";
import { useSignalRef } from "./vue-adapter";

const a = signal(0);
const b = signal(0);

const va = useSignalRef(a); // Vue ref
const vb = useSignalRef(b);

async function run() {
  await transaction(async () => {
    a.set(va.value + 1);
    await Promise.resolve(); // Simulate await
    b.set(vb.value + 1);
  }); // One flush, one rerun
}
</script>

<template>
  <p>a={{ va }} / b={{ vb }}</p>
  <button @click="run">+a, await, +b (one rerun)</button>
</template>

Enter fullscreen mode Exit fullscreen mode

Local Draft + Commit Once on Submit

<script setup lang="ts">
import { ref, watch } from "vue";
import { signal } from "../core/signal.js";
import { transaction } from "../core/scheduler.js";
import { useSignalRef } from "./vue-adapter";

const titleSig = signal("Hello");

const committed = useSignalRef(titleSig); // Read external value
const draft = ref(committed.value); // Local Vue state draft

// Optional: sync the draft when the external value changes
watch(committed, v => (draft.value = v));

async function save() {
  await transaction(() => {
    titleSig.set(draft.value); // Commit back once
  });
}
</script>

<template>
  <input v-model="draft" />
  <button @click="save">Save</button>
  <p>committed: {{ committed }}</p>
</template>

Enter fullscreen mode Exit fullscreen mode

Reminder:
Vue’s <Transition> and animations only affect display timing.
They do not delay data writes.
For merging data commits, use transaction(async).
If you want heavy UI regions to update later, handle that at the UI layer with delayed rendering or separated display regions.

Conceptual Summary

Data Layer

Wrap multi-step writes across await boundaries in transaction(async).

Result: one effect rerun.

UI Layer

Transitions and animations control presentation timing.

Do not expect them to change when signal.set() happens.

Draft Pattern

During editing, use component-local state or local signals.

When submitting, enter a transaction and commit back to the global signal once.

Understanding the Timeline Across await

transaction timeline

The key idea is:

  • Without a transaction, every await boundary gives the scheduler a chance to flush.

  • With a transaction, scheduled effects are held until the outermost transaction completes.

  • That means the effect sees the final consistent state instead of intermediate states.

Conclusion

In this article, we turned “multi-step updates across await boundaries” into a single side-effect rerun.

  • transaction(async) shares the same depth counter as the existing batch().
  • flushJobs() only runs when the outermost transaction exits.
  • computed remains lazy: it is only marked stale and never recomputed early.
  • Nested and exceptional cases are handled safely.
  • The current API and mental model remain intact.

In the next article, we will upgrade “merging” into “atomicity”.

If something fails, the state should roll back to what it was before entering the transaction.

In short:

This article solves the “run once” problem.

The next article solves the “all or nothing” problem.