Th?nk And Grow - Others - Others https://blog.thnkandgrow.com/category/uncategorized/ Let's Do It! Sat, 21 Mar 2026 10:13:55 +0000 vi hourly 1 https://wordpress.org/?v=6.9.4 https://d1gj38atnczo72.cloudfront.net/wp-content/uploads/2024/04/18114102/cropped-thnkandgrow-logo-32x32.jpg Th?nk And Grow - Others - Others https://blog.thnkandgrow.com/category/uncategorized/ 32 32 LiteLLM vs CliProxyAPI: Safe Integration Guide 2026 https://blog.thnkandgrow.com/litellm-vs-cliproxyapi-safe-integration-guide-2026/ Sat, 21 Mar 2026 10:13:55 +0000 https://blog.thnkandgrow.com/?p=3454 Combining LiteLLM with CliProxyAPI sounds powerful — but done wrong, it can expose your API keys and user data to serious risk. This guide breaks down exactly how these two tools differ, where each fits in your stack, and the safest integration pattern to use in production. If you're routing LLM traffic across multiple providers, getting this architecture right isn't optional — it's the difference between scalable infrastructure and a costly security incident.

The post LiteLLM vs CliProxyAPI: Safe Integration Guide 2026 appeared first on Th?nk And Grow.

]]>
Managing LLM APIs in production has become one of the most pressing infrastructure challenges for development teams in 2026. As more applications embed AI capabilities, the need for reliable, cost-efficient, and secure API routing has exploded. Two tools that frequently appear in the same conversation — especially among Vietnamese and Asian developer communities — are LiteLLM and CliProxyAPI. While they serve overlapping but distinct purposes, combining them without a clear security strategy can introduce serious risks. This guide breaks down what each tool does, how they compare, and how to integrate them safely in a production environment.

What Is LiteLLM? Core Features and Strengths

LiteLLM is an open-source Python library and self-hostable proxy server developed by BerriAI. Its core value proposition is simple: give developers a single, unified OpenAI-compatible interface to call over 100 LLM providers — including OpenAI, Anthropic Claude, Google Gemini, AWS Bedrock, Azure OpenAI, Groq, Mistral, Ollama, and many more — without rewriting application code for each provider.

Beyond basic API unification, LiteLLM ships with a comprehensive set of production-grade features:

  • Load balancing: Distribute requests across multiple models or providers to maximize availability and throughput.
  • Cost tracking and budget management: Set per-key or per-team spending limits, with real-time cost visibility across all providers.
  • Virtual API keys: Issue internal keys that map to real provider credentials, so downstream services never touch your actual API keys.
  • Rate limiting and retry logic: Protect against quota exhaustion and handle transient failures gracefully.
  • Caching: Redis-backed or in-memory caching to avoid redundant LLM calls and reduce costs.
  • Observability integrations: Native support for Langfuse, Helicone, and other logging platforms for full request/response audit trails.
  • RBAC and SSO: Enterprise-grade role-based access control for team environments.
  • Kubernetes deployment: Official Helm charts for scalable, cloud-native deployments.

In terms of community traction, LiteLLM has grown to over 13,000 GitHub stars and consistently records more than 10 million monthly downloads on PyPI, with multiple releases shipped every week. It is, by any measure, the most mature open-source LLM gateway available today.

What Is CliProxyAPI? Understanding Its Role

CliProxyAPI (available at github.com/router-for-me/CLIProxyAPI) is a CLI-oriented proxy tool designed to route and manage LLM API calls through an intermediary layer. Unlike LiteLLM’s comprehensive gateway approach, CliProxyAPI is a lightweight tool — focused on providing an OpenAI-compatible endpoint that proxies requests to underlying LLM providers, often with simplified configuration via command-line arguments.

It has gained particular traction among developers in Vietnam and across Southeast and East Asia, primarily because it addresses a set of very practical, ground-level problems:

  • Bypassing geographic restrictions: Several major LLM providers restrict API access by region. CliProxyAPI allows developers to route traffic through servers in permitted regions, enabling access that would otherwise be blocked.
  • Cost sharing and simplified billing: Teams or communities can pool access through a shared proxy endpoint, reducing individual overhead.
  • Simplified authentication: Users interact with a single proxy endpoint rather than managing multiple provider credentials directly.
  • OpenAI-compatible interface: Any tool or library that speaks the OpenAI API format can point to a CliProxyAPI endpoint with minimal reconfiguration.

It is important to distinguish between self-hosted instances of CliProxyAPI — where you run the tool on your own server — and third-party hosted CliProxyAPI services operated by others. The security implications of these two deployment modes are vastly different, as we will explore shortly.

LiteLLM vs CliProxyAPI: Key Differences Compared

Understanding where these tools diverge helps clarify why combining them requires deliberate architectural thinking rather than ad-hoc configuration.

Scope and Feature Set

LiteLLM is a full-featured API gateway with enterprise capabilities: RBAC, budget enforcement, multi-provider load balancing, caching, and deep observability. CliProxyAPI is a lightweight proxy layer — lean by design, optimized for quick setup and access routing rather than governance or cost management at scale.

Control and Data Ownership

When you self-host LiteLLM on your own infrastructure, you maintain complete ownership of every request and response. No data leaves your environment unless you explicitly configure it to. With third-party hosted CliProxyAPI services, your prompts, responses, and potentially your provider API keys pass through infrastructure you do not control — a significant consideration for any team handling sensitive data.

Target Use Cases

LiteLLM is built for team and enterprise environments where cost governance, provider redundancy, and auditability are non-negotiable. CliProxyAPI fits the profile of an individual developer or small team needing fast, low-friction access to LLM APIs — particularly when direct provider access is geographically or financially constrained.

Security Risks to Know Before Combining Both Tools

Before wiring these two tools together, every team should have an honest conversation about the following risks:

  • API key exposure: If you configure LiteLLM to route through a third-party CliProxyAPI service using your real provider API keys, those keys are transmitted to — and potentially logged by — infrastructure you do not own. A single misconfigured or malicious proxy can drain your API quota or expose billing credentials.
  • Data privacy: Every prompt and response passing through an intermediary is a potential data leak. For applications handling personal information, medical data, or proprietary business logic, this is a compliance risk, not just a technical one.
  • Rate limit abuse and quota leakage: Shared proxy endpoints may be used by many parties simultaneously. Your quota could be consumed by other users on the same proxy, leading to unexpected rate limiting or cost overruns on your provider account.
  • Unverified endpoints: Community-shared proxy URLs — common in developer forums and Telegram groups — carry no guarantees of uptime, integrity, or security. Using them in production is equivalent to routing your application traffic through an unknown third party.

Rule of thumb: If you did not deploy the proxy server yourself, treat it as untrusted infrastructure. Never send real provider API keys or sensitive prompts through it without explicit security controls in place.

How to Safely Combine LiteLLM and CliProxyAPI

The safest integration pattern treats LiteLLM as the control plane and CliProxyAPI as a backend provider endpoint — one of potentially many — that LiteLLM routes to under specific conditions. This keeps all governance, key management, and observability centralized in LiteLLM, while CliProxyAPI handles only the routing layer it was designed for.

1. Secure Key Management

Never hardcode API keys in configuration files. Use environment variables at minimum, and prefer dedicated secret managers in production:

  • HashiCorp Vault for self-hosted secret management
  • AWS Secrets Manager or Google Secret Manager for cloud-native deployments
  • Doppler for developer-friendly environment variable management across environments

2. Use LiteLLM Virtual Keys

Issue virtual keys to all downstream services and team members. Real provider credentials stay inside LiteLLM’s secure configuration layer and are never exposed to application code or external services.

3. Enable Full Observability

Connect LiteLLM to Langfuse or Helicone to log every request routed through CliProxyAPI. This gives you a complete audit trail and makes anomaly detection possible.

Practical Example: Sample Configuration Setup

Here is a minimal but realistic config.yaml for LiteLLM that routes requests through a self-hosted CliProxyAPI endpoint, with budget limits and logging enabled:

model_list:
  - model_name: gpt-4o-via-cliproxy
    litellm_params:
      model: openai/gpt-4o
      api_base: https://your-self-hosted-cliproxy.example.com/v1
      api_key: os.environ/CLIPROXY_API_KEY

  - model_name: claude-3-5-sonnet
    litellm_params:
      model: anthropic/claude-3-5-sonnet-20241022
      api_key: os.environ/ANTHROPIC_API_KEY

router_settings:
  routing_strategy: least-busy
  fallbacks:
    - gpt-4o-via-cliproxy: [claude-3-5-sonnet]

litellm_settings:
  success_callback: ["langfuse"]
  failure_callback: ["langfuse"]

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL

environment_variables:
  LANGFUSE_PUBLIC_KEY: os.environ/LANGFUSE_PUBLIC_KEY
  LANGFUSE_SECRET_KEY: os.environ/LANGFUSE_SECRET_KEY

To start the LiteLLM proxy server with this configuration:

litellm --config config.yaml --port 4000 --detailed_debug

This setup ensures that CliProxyAPI is just one backend option among many, with automatic fallback to Anthropic Claude if the proxy endpoint is unavailable. All traffic is logged to Langfuse, and no real keys are exposed downstream.

Best Practices for Production Deployment

  • Self-host LiteLLM on your own infrastructure. Use Docker Compose for smaller deployments or Kubernetes with the official Helm chart for production scale. Never rely on a shared or third-party LiteLLM instance for sensitive workloads.
  • Implement RBAC and per-key budget limits. Assign virtual keys with explicit spending caps to each team, service, or environment. This prevents a single runaway process from exhausting your entire monthly budget.
  • Enable Redis caching. Repeated identical prompts — common in development and testing — can be served from cache rather than forwarded to CliProxyAPI or any upstream provider, cutting costs significantly.
  • Configure fallback routing. Define at least one alternative provider for every model alias. If your CliProxyAPI endpoint goes down, LiteLLM should automatically route to a direct provider without manual intervention.
  • Rotate API keys regularly. Establish a rotation schedule for both real provider keys and LiteLLM virtual keys. Audit access logs after each rotation to detect any anomalies.
  • Only use self-hosted CliProxyAPI instances. If geographic routing is genuinely required, deploy your own CliProxyAPI instance on a VPS or cloud VM in the target region. This keeps data flow within infrastructure you control.

When to Use LiteLLM Alone vs Combined with CliProxyAPI

Not every team needs both tools. Here is a practical decision framework:

Use LiteLLM Standalone When:

  • Your team has direct, unrestricted access to major LLM providers.
  • Data sovereignty and compliance are top priorities — every request must stay within controlled infrastructure.
  • You need enterprise features like RBAC, SSO, and audit logging without additional complexity.

Consider Adding CliProxyAPI When:

  • Geographic restrictions genuinely prevent direct provider access from your deployment region.
  • You are self-hosting the CliProxyAPI instance and can verify the full data path.
  • Cost constraints make direct provider access impractical for development or testing environments.

Evaluate Alternatives First:

Before adding CliProxyAPI to your stack, consider whether OpenRouter or One API might serve the same purpose with greater transparency and community accountability. OpenRouter in particular offers a well-documented, commercially operated unified API layer that is easier to audit than an unknown community proxy.

Conclusion: Security-First LLM API Architecture in 2026

LiteLLM and CliProxyAPI address real and distinct problems in the LLM API management landscape. LiteLLM is a mature, enterprise-ready gateway that gives teams full control over routing, costs, and observability. CliProxyAPI is a lightweight access layer that solves practical geographic and cost barriers — but comes with security tradeoffs that cannot be ignored.

When combining both tools, the guiding principle is clear: LiteLLM is your control plane, and CliProxyAPI is just one backend endpoint it manages. All key management, access control, budget enforcement, and logging must live in LiteLLM. CliProxyAPI — especially if third-party hosted — should never be trusted with real provider credentials or sensitive data.

The teams that build reliable, cost-efficient LLM applications in 2026 are not the ones who find the fastest shortcut to an API endpoint. They are the ones who treat every proxy layer as a potential risk surface, instrument everything with observability, and maintain clear ownership of every byte that flows through their AI infrastructure.

Start with self-hosted LiteLLM, secure your keys, enable your audit logs, and only introduce CliProxyAPI — or any proxy layer — when you can verify exactly where your data goes. That discipline is what separates a production-grade LLM architecture from a security incident waiting to happen.

The post LiteLLM vs CliProxyAPI: Safe Integration Guide 2026 appeared first on Th?nk And Grow.

]]>
Nitro App Hooks in NuxtJS: A Complete Guide https://blog.thnkandgrow.com/nitro-app-hooks-nuxtjs-complete-guide/ Thu, 19 Mar 2026 04:40:46 +0000 https://blog.thnkandgrow.com/nitro-app-hooks-nuxtjs-complete-guide/ Ever wished you could tap into NuxtJS's server lifecycle without touching the core? This guide walks you through Nitro App Hooks — from build-time configurations to runtime plugins — covering real-world use cases like centralized logging, auth middleware, and database management. Master these hooks and you'll have full control over your server behavior across 20+ deployment targets, all without breaking a sweat.

The post Nitro App Hooks in NuxtJS: A Complete Guide appeared first on Th?nk And Grow.

]]>
If you’ve been building applications with NuxtJS 3, you’ve likely heard the name Nitro thrown around — but understanding what it actually does under the hood, and more importantly, how to leverage its powerful hooks system, can genuinely transform the way you architect your server-side logic. Nitro is the high-performance server engine that powers NuxtJS 3, handling everything from request processing and static asset generation to multi-platform deployment. And at the heart of its extensibility model lies a clean, type-safe system of hooks that gives developers precise control over the entire server lifecycle without ever touching core framework code. In this guide, we’ll go deep into Nitro App Hooks — what they are, how they work, and how to use them effectively in real-world NuxtJS 3 applications.

What Are Nitro App Hooks?

Nitro is an open-source server toolkit built by the UnJS team. It serves as the universal server engine for NuxtJS 3, abstracting away deployment complexity and providing a consistent runtime across more than 20 deployment targets — from Node.js and Vercel to Cloudflare Workers and AWS Lambda. When you run nuxt build, Nitro is what compiles your server-side code into an optimized, portable output ready for any of these environments.

Within this engine, hooks are predefined interception points in the application lifecycle. Think of them as event listeners attached to specific moments in the server’s existence — when a request arrives, before a response is sent, when an error is thrown, or when the server shuts down. Nitro’s hooks system is powered internally by hookable, another UnJS library, which provides a lightweight yet powerful pub/sub mechanism for lifecycle events.

It’s important to distinguish between two categories of hooks in the Nitro/Nuxt ecosystem:

  • Build-time hooks: These fire during the build process (e.g., nitro:init, nitro:build:before). They are registered in nuxt.config.ts and allow you to modify Nitro’s configuration or behavior before the server bundle is compiled.
  • Runtime hooks (App hooks): These fire while the server is actively running and handling traffic. They are registered through Nitro plugins inside the server/plugins/ directory and represent the primary focus of this guide.

The core benefits of this architecture are significant. You get a plugin-based extensibility model that keeps your codebase modular, full TypeScript type safety with well-defined event and error object shapes, and true composability — you can combine multiple hooks across multiple plugins to build sophisticated server behaviors without coupling concerns together.

The Most Important Nitro App Hooks

Nitro exposes a rich set of hooks across both the build and runtime phases. Here’s a structured overview of the ones you’ll use most frequently:

Lifecycle Hooks (Build-time)

  • nitro:init — Fires when the Nitro instance is initialized during build. Ideal for modifying the Nitro config programmatically.
  • nitro:build:before — Fires before the build process starts. Useful for pre-build validations or injecting environment-specific settings.
  • nitro:close — Fires when the Nitro instance is closed after build. Good for cleanup tasks in CI/CD pipelines.

Runtime / App Hooks

  • request — Fires on every incoming HTTP request. This is your primary hook for middleware-like logic such as authentication, rate limiting, and logging.
  • beforeResponse — Fires just before the response is sent to the client. Use this to mutate response headers or body.
  • afterResponse — Fires after the response has been sent. Ideal for non-blocking tasks like analytics tracking.
  • error — Fires whenever an unhandled error occurs. Critical for centralized error reporting.
  • close — Fires when the server is shutting down. Use this to gracefully close database connections or flush logs.

Render Hooks (SSR)

  • render:response — Fires when a server-rendered response is being assembled. Allows you to inspect or modify the full response object.
  • render:html — Fires when the HTML output of an SSR render is ready. Useful for injecting custom scripts, meta tags, or modifying the HTML structure.

How to Register and Use Hooks in NuxtJS

There are two primary methods for registering hooks, and choosing the right one depends on whether you’re working at build time or runtime.

Method 1: Nitro Plugin (Recommended for Runtime Hooks)

For runtime hooks, the recommended approach is to create a plugin file inside the server/plugins/ directory. NuxtJS automatically discovers and registers any files placed here. The naming convention is straightforward — use a descriptive, lowercase filename like logger.ts or errorHandler.ts.

// server/plugins/logger.ts
export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('request', (event) => {
    console.log(`[${new Date().toISOString()}] ${event.method} ${event.path}`)
  })

  nitroApp.hooks.hook('close', () => {
    console.log('Server is shutting down...')
  })
})

The defineNitroPlugin helper provides full TypeScript inference for the nitroApp parameter, making it easy to explore available hooks and their payloads directly in your editor.

Method 2: nuxt.config.ts (For Build-time Hooks)

Build-time hooks are declared directly in your nuxt.config.ts file under the hooks property. This is the appropriate place for hooks that need to interact with the Nitro configuration object during the build phase.

// nuxt.config.ts
export default defineNuxtConfig({
  hooks: {
    'nitro:init': (nitro) => {
      console.log('Nitro initialized with config:', nitro.options.preset)
    },
    'nitro:build:before': (nitro) => {
      // Modify nitro options before build
      nitro.options.timing = true
    }
  }
})

Pro tip: Keep build-time hooks in nuxt.config.ts and runtime hooks in server/plugins/. Mixing them leads to confusing code and potential issues with hot module replacement during development.

Real-World Use Cases

Understanding the API is one thing — seeing it applied to real problems is where the value truly becomes apparent. Here are the most impactful use cases you’ll encounter in production applications.

Logging and Performance Monitoring

One of the first things any production server needs is observability. With the request hook, you can instrument every incoming request with minimal overhead:

// server/plugins/logger.ts
export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('request', (event) => {
    const start = Date.now()

    event.node.res.on('finish', () => {
      const duration = Date.now() - start
      console.log(`${event.method} ${event.path} — ${event.node.res.statusCode} [${duration}ms]`)
    })
  })
})

This pattern captures both the request metadata and the actual response time, giving you the data you need for performance dashboards without relying on external APM agents at the infrastructure level.

Centralized Error Handling

Instead of scattering try/catch blocks across your API routes, the error hook provides a single place to capture, format, and forward all server errors to your monitoring platform of choice:

// server/plugins/errorHandler.ts
export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('error', (error, { event }) => {
    // Forward to Sentry, Datadog, or any observability platform
    console.error({
      timestamp: new Date().toISOString(),
      url: event?.path,
      method: event?.method,
      message: error.message,
      stack: error.stack
    })
  })
})

Authentication Middleware

For applications with protected API routes, the request hook acts as a natural gateway for JWT validation or session checking:

// server/plugins/auth.ts
export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('request', async (event) => {
    if (event.path.startsWith('/api/protected')) {
      const authHeader = getHeader(event, 'Authorization')
      if (!authHeader?.startsWith('Bearer ')) {
        throw createError({ statusCode: 401, statusMessage: 'Unauthorized' })
      }
      // Validate token logic here
    }
  })
})

Database Connection Management

Managing database connections at the server level — rather than per-request — is a critical performance pattern. Nitro hooks make this clean and reliable:

// server/plugins/database.ts
export default defineNitroPlugin(async (nitroApp) => {
  const db = await connectToDatabase(process.env.DATABASE_URL!)
  console.log('Database connected successfully')

  nitroApp.hooks.hook('close', async () => {
    await db.disconnect()
    console.log('Database connection closed gracefully')
  })
})

Response Transformation

The beforeResponse hook is ideal for adding security headers, CORS policies, or custom metadata to every outgoing response — keeping this logic centralized rather than duplicated across route handlers:

// server/plugins/responseHeaders.ts
export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('beforeResponse', (event, { body }) => {
    setResponseHeader(event, 'X-Powered-By', 'MyApp/1.0')
    setResponseHeader(event, 'X-Content-Type-Options', 'nosniff')
  })
})

Best Practices When Working with Nitro Hooks

As with any powerful tool, discipline in how you use Nitro hooks makes the difference between a maintainable codebase and a tangled mess of side effects.

  • Single Responsibility per Plugin: Each plugin file should do exactly one thing. A logger.ts handles logging, an auth.ts handles authentication. This makes debugging, testing, and replacing individual behaviors straightforward.
  • Always handle async correctly: Nitro supports async hook handlers, but unhandled promise rejections can silently swallow errors. Always use try/catch inside async hooks or ensure your error surfaces through the error hook.
  • Leverage TypeScript fully: The event, error, and nitroApp objects all have well-defined types. Use them. Your IDE will thank you, and you’ll catch type mismatches at compile time rather than in production.
  • Keep the request hook lean: This hook fires on every single request. Heavy synchronous computations or blocking I/O here will directly degrade your server’s throughput. Defer non-critical work to afterResponse where possible.
  • Use the close hook for cleanup: Never rely on process exit signals alone for resource cleanup. The close hook is the proper, framework-aware way to release database connections, flush log buffers, or cancel scheduled tasks.

Nitro Hooks and the UnJS Ecosystem

Nitro doesn’t exist in isolation — it’s part of a broader ecosystem of composable, framework-agnostic libraries under the UnJS umbrella. Understanding these relationships helps you build more effectively and debug more confidently.

At the HTTP layer, Nitro uses H3 as its request/response framework. When you access event inside a hook, you’re working with an H3 H3Event object. Utilities like getHeader, setResponseHeader, and createError all come from H3. The hooks system itself is powered by hookable, which provides the underlying pub/sub mechanism. This means if you ever need to create your own hookable systems in your application, you can use the same library.

One of Nitro’s most compelling strengths is its universal deployment model. The same hook code you write for your local Node.js development server will work identically on Vercel Edge, Cloudflare Workers, or AWS Lambda — because Nitro abstracts away the platform-specific runtime details. This is a significant architectural advantage for teams that need deployment flexibility.

In Nitro v2.x, several exciting capabilities have been added. Native WebSocket support via hooks enables real-time features without additional middleware layers. Task scheduling (currently experimental) allows you to define cron-like background jobs within the Nitro runtime. And deeper integration with SQL databases through the unstorage and database connector APIs is making Nitro increasingly capable as a full backend runtime, not just an SSR middleware layer.

As edge computing continues to mature, Nitro’s architecture positions NuxtJS 3 applications to take full advantage of globally distributed runtimes. Hooks that run at the edge — with sub-millisecond cold starts and geographic proximity to users — represent the direction the entire ecosystem is moving.

Conclusion

Nitro App Hooks represent one of the most elegant and underutilized features in the NuxtJS 3 ecosystem. They give you structured, type-safe, and composable control over every meaningful moment in your server’s lifecycle — from the first request to graceful shutdown — without requiring you to fork the framework or fight against its abstractions. By registering runtime hooks through Nitro plugins and build-time hooks through nuxt.config.ts, you can layer sophisticated behaviors like centralized logging, global error reporting, authentication gating, and database lifecycle management cleanly onto your application.

If you’re just getting started with Nitro hooks, the best path forward is incremental. Begin with a simple request logger to understand how event objects flow through the system. Then add a centralized error handler to gain visibility into what’s failing in production. Once those feel comfortable, you’ll have the mental model needed to tackle more advanced patterns like authentication middleware, response transformation, and graceful resource management.

The investment in learning Nitro’s hooks system pays dividends that compound over time — your server-side code becomes more modular, your team can reason about behaviors in isolation, and your application becomes genuinely portable across deployment targets. That’s the kind of architectural foundation worth building on.

The post Nitro App Hooks in NuxtJS: A Complete Guide appeared first on Th?nk And Grow.

]]>
Plan with Opus, Code with Sonnet: The opusplan Guide https://blog.thnkandgrow.com/plan-with-opus-code-with-sonnet-opusplan-guide/ Tue, 17 Mar 2026 17:40:33 +0000 https://blog.thnkandgrow.com/plan-with-opus-code-with-sonnet-opusplan-guide/ Learn how opusplan uses Claude Opus for smart task planning and Claude Sonnet for coding — a smarter LLM routing strategy for agentic AI workflows.

The post Plan with Opus, Code with Sonnet: The opusplan Guide appeared first on Th?nk And Grow.

]]>
Every developer who has worked with AI coding assistants knows the frustrating trade-off: use the most powerful model and watch your API bill skyrocket, or use the faster, cheaper model and accept that your architectural decisions might be… let’s say, optimistic. It feels like choosing between a Ferrari and a fuel-efficient sedan when what you actually need is both — a Ferrari for the highway and a sensible car for city driving.

This is exactly the problem that opusplan solves. Built directly into Claude Code, it’s a deceptively simple feature that reflects a genuinely smart philosophy: not all AI tasks are created equal, so why treat them the same? By automatically routing your planning work to Claude Opus and your implementation work to Claude Sonnet, opusplan eliminates the manual model-switching dance and lets you focus on what actually matters — building great software.

In this guide, we’ll break down how opusplan works, why the planning/implementation split makes sense both technically and economically, and how to start using it in your real-world projects today.


What Is opusplan and How Does It Work?

First, let’s clear up a common misconception: opusplan is not a separate AI model. It’s a special model alias built into Claude Code — essentially a smart routing layer that sits between you and Anthropic’s model lineup.

Here’s the core mechanism:

  • When you activate Plan Mode (via Shift + Tab), opusplan routes your session to Claude Opus 4.5/4.6 — Anthropic’s most powerful, reasoning-heavy model.
  • When you exit Plan Mode to begin actual coding and implementation, the alias automatically switches to Claude Sonnet 4.5/4.6 — faster, more cost-efficient, and optimized for code generation throughput.

The workflow looks like this:

Enter Plan Mode (Shift + Tab) → Opus takes over → Deep reasoning, architecture, analysis → Exit Plan Mode → Sonnet takes over → Fast, high-quality code generation → Repeat as needed

No manual switching. No remembering which model you’re on. The alias handles the routing entirely based on which phase you’re in. It’s a small UX decision with surprisingly large downstream effects on both quality and cost.


Why Separate Planning From Implementation?

Before we get into the economics, it’s worth asking: is this separation actually necessary, or is it just a clever marketing angle? The answer is rooted in both software engineering best practices and the fundamental nature of how large language models work.

Planning Demands Deep Reasoning

Good architectural planning is cognitively expensive. When you’re designing a new feature, refactoring a legacy system, or debugging a subtle race condition, you need:

  • Holistic understanding of the existing codebase and its constraints
  • The ability to reason about trade-offs across multiple dimensions simultaneously
  • Risk analysis — what could go wrong, and how do we mitigate it?
  • The foresight to anticipate edge cases before a single line of code is written

This is exactly where Claude Opus excels. Its larger parameter count and deeper reasoning capabilities mean it can hold more context in “working memory,” reason through complex interdependencies, and produce plans that are genuinely robust rather than superficially plausible.

Implementation Demands Speed and Throughput

Once you have a solid plan, the implementation phase has a very different character. You’re executing a known strategy — writing functions, generating boilerplate, creating tests, updating configuration files. This is repetitive, high-volume work where speed and reliability matter more than deep philosophical reasoning.

Claude Sonnet is purpose-built for this. It generates code faster, handles more tokens per dollar, and for well-defined implementation tasks, its output quality is essentially indistinguishable from Opus. You’re not paying a premium for reasoning horsepower you don’t need at this stage.

This Is Just Good Engineering Practice

Software engineers have long known that the most expensive bugs are the ones baked into the architecture. A bug in a line of code costs minutes to fix. A bug in the system design can cost weeks or months. opusplan essentially encodes this wisdom into your AI workflow: think hard first, then execute efficiently.


The Dual Benefit: Higher Quality and Lower Cost

Let’s talk numbers, because this is where opusplan becomes genuinely compelling for teams managing AI API budgets.

Claude Opus is significantly more expensive per token than Claude Sonnet. In a typical development session, the planning phase generates far fewer tokens — you’re producing a structured plan, not thousands of lines of code. The implementation phase is where token volume explodes — multiple files, functions, tests, documentation.

Consider three scenarios for building a complex feature:

  • Pure Opus: Maximum quality planning AND implementation, but you’re paying Opus prices for every token of boilerplate code. Expensive, and often overkill for the implementation phase.
  • Pure Sonnet: Fast and cheap, but your architectural decisions lack the depth that Opus provides. You might save money upfront and pay for it later in technical debt.
  • opusplan: Opus for the high-value, low-token planning phase. Sonnet for the high-volume, lower-complexity implementation phase. You get the best reasoning where it matters most, and the best economics where volume is highest.

The ROI calculation is straightforward: use your most expensive resource for your highest-leverage work. This is the same principle behind having senior engineers do architecture reviews rather than writing CRUD endpoints all day.


How to Activate opusplan in Claude Code

Getting started is refreshingly simple. There are two ways to use opusplan:

Option 1: Activate During a Session

Within any active Claude Code session, simply type:

/model opusplan

This switches your current session to use the opusplan alias immediately. From this point forward, Shift + Tab will toggle Plan Mode and trigger the automatic model switching behavior.

Option 2: Set as Default in settings.json

If you want opusplan to be your default model for every Claude Code session, add it to your configuration file:

{
  "model": "opusplan"
}

With this setting in place, you never have to think about it again. Every session starts with opusplan active, and the Plan Mode toggle (Shift + Tab) automatically routes to Opus when you need deep thinking and back to Sonnet when you’re ready to build.

Pro tip: Even if you set opusplan as your default, it’s worth being intentional about when you enter and exit Plan Mode. The quality of your Opus planning session directly determines the quality of Sonnet’s implementation. Don’t rush through it.


Real-World Use Cases Where opusplan Shines

Theory is useful, but let’s ground this in the kinds of tasks you actually face as a developer.

Large-Scale Refactoring

Imagine you’re modernizing a 40,000-line legacy codebase — moving from a callback-heavy architecture to async/await, or migrating from a monolith to a service-oriented design. This is exactly where the plan/implement split pays dividends.

In Plan Mode, Opus analyzes the existing architecture, identifies coupling hotspots, designs the migration path, and flags high-risk areas. When you switch to implementation, Sonnet executes the refactoring file by file, applying the strategy Opus designed. You get a coherent migration plan executed efficiently — not a haphazard series of changes that creates new problems.

Designing Complex Features

Building a real-time collaboration feature, a payment processing system, or a complex data pipeline? These features have non-obvious failure modes and architectural decisions that ripple across the entire codebase. Let Opus design the data models, define the API contracts, plan the state management strategy, and reason through the edge cases. Then let Sonnet write the actual code, knowing it’s working from a solid blueprint.

Debugging Hard Problems

Race conditions, memory leaks, intermittent production failures — these are the bugs that resist brute-force debugging. In Plan Mode, Opus can perform deep analysis: forming hypotheses, reasoning about execution order, identifying the minimal reproduction case. Once Opus has a clear theory and investigation strategy, Sonnet writes the fix, adds regression tests, and updates relevant documentation.

Architecture Reviews and Technical Debt Assessment

Should you migrate to microservices? Is your current database schema going to scale? Which technical debt items should you tackle in the next sprint? These are high-stakes judgment calls. Opus can analyze trade-offs with nuance and produce a prioritized, reasoned recommendation. Sonnet then handles the execution work — generating boilerplate, configuration files, CI/CD pipeline updates — once the direction is clear.


opusplan vs. Other AI Coding Tools

It’s worth putting opusplan in context against the broader AI coding tool landscape, because the automatic phase-based switching is genuinely unusual.

  • GitHub Copilot: Operates with a single model per session. No concept of planning vs. implementation phases.
  • Cursor: Allows manual model selection per request, which is powerful but requires constant conscious decisions from the developer.
  • Aider: Supports a --model flag for model selection, but switching requires manual intervention and there’s no built-in phase awareness.
  • Continue.dev: Offers manual model routing configuration, but again, the developer is responsible for the routing logic.

opusplan stands apart because the switching is automatic and phase-aware. You don’t have to remember which model you’re using or make a conscious decision to switch. The tool infers the right model from your current working mode.

This points to a larger trend in the AI industry: multi-model agentic pipelines. Tools like RouteLLM and LiteLLM are building sophisticated routing layers that direct requests to appropriate models based on complexity, cost constraints, and task type. opusplan is an early, developer-friendly implementation of this idea — and it hints at where AI coding assistants are heading. The future isn’t a single model that does everything; it’s an intelligent orchestration layer that deploys the right model for each task.


Conclusion: The Right Tool for the Right Job

opusplan is a small feature with a big idea behind it. It’s not just about saving money on API calls (though it does that). It’s not just about getting better planning output (though it does that too). At its core, it reflects a fundamental principle of good engineering: match your tools to your tasks.

We’ve always known that the planning phase of software development deserves more investment than it typically receives. opusplan makes it structurally easier to honor that principle — by automatically deploying your most capable AI model precisely when you need deep reasoning, and stepping back to a faster, more economical model when you need execution speed.

For individual developers, this means better architectural decisions without budget anxiety. For teams, it means a more consistent, disciplined workflow where planning is treated as a first-class activity rather than an afterthought. And for anyone watching the broader AI landscape, it’s a preview of how sophisticated multi-model orchestration will become a standard part of the developer toolkit.

The next time you sit down to tackle a complex refactor, design a new feature, or investigate a gnarly bug, try this: open Claude Code, set /model opusplan, hit Shift + Tab to enter Plan Mode, and let Opus think through the problem with you. When you have a plan you trust, exit Plan Mode and let Sonnet execute it. You might be surprised how much better the output is — and how much more confident you feel about the code you’re shipping.

Give it a try in your next project. The trade-off between quality and cost just became a lot less painful.

The post Plan with Opus, Code with Sonnet: The opusplan Guide appeared first on Th?nk And Grow.

]]>
Từ Bế Tắc Debugging Đến Kiểm Soát Hoàn Toàn: Hành Trình Xây Dựng React Debugger Extension https://blog.thnkandgrow.com/vi/hanh-trinh-xay-dung-react-debugger-extension/ Mon, 09 Feb 2026 14:57:33 +0000 https://blog.thnkandgrow.com/?p=2672 Nhật ký hậu trường: Vì sao debug React khiến tôi cạn kiệt năng lượng – và React Debugger đã kéo tôi ra khỏi vòng lặp vô tận đó Có một ngày thứ Ba tưởng như bình thường: tôi nhận một báo cáo khá mơ hồ – trang thanh toán Next.js đôi lúc trắng xóa khi […]

The post Từ Bế Tắc Debugging Đến Kiểm Soát Hoàn Toàn: Hành Trình Xây Dựng React Debugger Extension appeared first on Th?nk And Grow.

]]>

Nhật ký hậu trường: Vì sao debug React khiến tôi cạn kiệt năng lượng – và React Debugger đã kéo tôi ra khỏi vòng lặp vô tận đó

Có một ngày thứ Ba tưởng như bình thường: tôi nhận một báo cáo khá mơ hồ – trang thanh toán Next.js đôi lúc trắng xóa khi refresh. Không có stack trace, error boundary không nhúc nhích, mọi thứ “chạy” nhưng UI biến mất. Tôi lao vào đặt console.log khắp nơi, bật Profiler của React DevTools, xem Performance tab của Chrome. Sau gần hai ngày quay cuồng, tôi mới phát hiện ra thủ phạm chỉ là một đoạn JSX render Date.now(), khiến HTML phía server lệch so với client. Đồng nghiệp QA đùa rằng “phải cúng bái code” mới xong. Nhưng ở góc nhìn của tôi, đây chỉ là một vòng lặp quen thuộc – debug React không chỉ đau đầu, nó còn ăn mòn năng lượng sáng tạo.

Bài viết này không phải là một bản PR khô khan. Tôi muốn kể lại hành trình loay hoay với các “con boss” của debugging React, những lần review code dài vô tận vẫn không nhìn ra nguyên nhân, và cách mà React Debugger – một extension DevTools do chính tay tôi xây dựng – giúp tôi cắt giảm hơn 60% thời gian đuổi theo bug. Tôi sẽ đi qua những lỗi nguy hiểm tiềm ẩn, ví dụ thực tiễn, phân tích giá trị cốt lõi của extension, đào sâu từng tab và tính năng, chia sẻ best practice, khẳng định độ tin cậy, rồi kết lại bằng lời hứa cá nhân tiếp tục cải tiến để cộng đồng React không còn phải “bán linh hồn” cho việc gỡ bug.


1. Debug React chưa bao giờ “dễ thương” trong mắt tôi

Hydration mismatch – “kẻ” khiến cả app trắng xóa

Trong các dự án Next.js, việc server-render và client-render khớp nhau là tối quan trọng. Thế nhưng những khác biệt tưởng như vô hại – Math.random() trong JSX, định dạng ngày theo locale, điều kiện typeof window !== 'undefined' – lại đủ để phá hỏng cả phiên. React log thông báo lạnh lùng “Hydration failed because the initial UI does not match…” và dừng lại. Tôi đã từng tốn hơn 20 giờ chỉ để tìm một component <Hero /> gọi Date.now() ở render đầu tiên. Cảm giác như mò kim đáy bể.

useEffect dependency hell & stale closure

useEffect, useCallback, useMemo vốn là cứu tinh, nhưng dependency thiếu/thừa hoặc không ổn định sẽ sinh ra vòng lặp render vô hạn, API gọi liên tục, dữ liệu “stale” cực kỳ khó đoán. Dan Abramov đã viết cả bài dài “A Complete Guide to useEffect”, ngầm thừa nhận rằng hook này là “đầu tàu” của nhiều vấn đề. Tôi nhận ra: không chỉ biết “nên” đưa gì vào dependency, mà còn phải biết khoảnh khắc nào effect bị kích hoạt, bởi input nào – điều mà DevTools mặc định không chỉ rõ.

“Re-render hell” & referential instability

Một component rerender 200 lần vì props nhận hàm inline tạo mới, Profiler chỉ bảo “component rerender”. Còn “tại sao” thì tôi phải tự so sánh props cũ/mới, context cũ/mới. Tôi nhớ lần audit một component “ProductList” rerender liên tục do parent truyền filters={{ category: 'all' }} được tạo mới mỗi render. Giải pháp chỉ là useMemo, nhưng để chứng minh: log diff, chụp snapshot, viết lại cả “hồ sơ” render. Công việc lặt vặt, tốn thời gian.

Race condition với async state

Người dùng chuyển tab nhanh, API tab A trả lời sau B, UI hiển thị sai. Muốn tái hiện bug phải log tay, gắn timestamp, đo đạc state thủ công… Trong khi tôi cần ship tính năng mới, việc “làm sản phẩm” trở thành xa xỉ.

State sync & prop drilling

Dù React khuyến cáo “lift state up”, nhưng khi state chia sẻ qua nhiều tầng hoặc context trùm cả app, việc truy vết “ai bắn state update” giống như theo dõi dây mơ rễ má. Tôi từng commit cả trăm dòng console.log chỉ để biết giá trị selectedUser dịch chuyển ra sao qua các component. Review cuối tuần? Một chuỗi diff vô nghĩa nhưng không thể bỏ.

Memory leak & layout shift

React cộng Chrome API, WebSocket, timers… nếu thiếu cleanup, heap memory tăng đều, app giật. DevTools Memory view giúp đo snapshot nhưng khó thao tác liên tục. Layout shift (CLS) thì càng “căng”: biết có vấn đề, nhưng không biết element nào gây shift.

Những vấn đề này ngốn hàng giờ, khiến code review biến thành “địa ngục diff”, còn năng lượng sáng tạo bị đốt sạch.


2. Hai câu chuyện thực tế (và cách thời gian bay màu trong tay tôi)

Case 1: Sidebar monitoring tool

  • Triệu chứng: Sidebar React freeze.
  • Trước: 14 giờ cắm đầu. Profiler báo Sidebar render lâu, nhưng trigger mơ hồ. Tôi viết script diff props, vẫn chỉ dừng ở phỏng đoán.
  • Sau khi dùng React Debugger: Mở Timeline Tab, filter render, chụp snapshot → UserMenu rerender 62 lần, trigger “context”. Click vào chi tiết thấy UserContext đổi key “theme” vì tôi viết value={{ theme: getTheme(), user }} ngay trong render. Sửa trong 10 phút.
  • Tiết kiệm: khoảng 10 giờ (71%).

Case 2: SSR hydration bug

  • Triệu chứng: Trang blog random trắng.
  • Trước: hơn 20 giờ, tôi so HTML server-client, thêm guard, log window.
  • Sau: Dùng Timeline Tab, bật correlation giữa render & error, click snapshot → extension highlight “Hydration mismatch – component Header -> difference tại Date.now()”. Tôi fix và QA xác nhận.
  • Tiết kiệm: khoảng 12 giờ (60%).

Kể từ khi đưa React Debugger vào workflow, thời gian debug giảm rõ rệt, PR nhẹ hơn, và quan trọng nhất: tinh thần tôi đỡ bị “hành”.


3. React Debugger Extension – “máy quét MRI” do chính tôi chế tạo

Tôi xây React Debugger dưới dạng extension DevTools, xuất hiện như một tab “React Debugger”. Nó không dừng ở việc ném cảnh báo, mà tạo nên hệ quan sát đầy đủ.

  1. Observability: Mọi sự kiện render, state change, effect, error, memory, context… đều được log với timestamp, trigger, component, stack.
  2. Correlation: Khi chọn một event, extension highlight các event liên quan, tạo narrative “vì sao nó xảy ra”.
  3. Actionable remediation: Issue card nêu rõ “làm gì để sửa” (ví dụ: “missing cleanup – thêm return () => clearInterval(id);”).
  4. Realtime overlay: React Scan highlight rerender ngay trên UI.
  5. Pattern detector: Tự động flag DIRECT_STATE_MUTATION, INDEX_AS_KEY, STALE_CLOSURE, INFINITE_LOOP_RISK, v.v.

Giá trị cốt lõi (3 trụ cột tôi đặt ra)

  • Context-aware: Không chỉ hiển thị con số, extension truy vết chuỗi nguyên nhân và thành phần liên quan.
  • Time-machine: Snapshot timeline, export JSON, so sánh trước/sau refactor.
  • Full-stack view: UI, performance, side effect, memory, layout shift, Redux… hội tụ trong một giao diện.

Nguồn thông tin:

  • README mô tả tính năng: UI & State Issues, Performance Analysis, Side Effects, CLS, Redux DevTools, Timeline, Memory.
  • DEBUGGING-GUIDE.md – hướng dẫn chi tiết từng tab, metric, workflow cho cấp độ fresher/mid/senior.

4. Giải phẫu từng tab & tính năng (trong mắt người tạo ra nó)

4.1 Timeline Tab – “dòng thời gian sự kiện”

Loại eventÝ nghĩa
🔄 RenderComponent render, ghi rõ trigger: state, props, context, parent, mount
📦 State changesetState, Redux action, context update (kèm tên state/hook index)
⚡ EffectuseEffect run/cleanup với dependency preview
❌ ErrorJS error, React error boundary, stack trace
🧠 MemorySnapshot heap, growth rate, spike indicator
🔗 Context changeProvider value thay đổi, các key bị đổi

Điểm mạnh:

  • Filter theo type, search component.
  • Snapshot timeline → export JSON, so sánh sau khi tối ưu.
  • Correlation panel highlight event liên quan (render – state change – effect).
  • Render detail hiển thị diff props/state (oldValue → newValue), render reason summary, fiber depth, parent component.
  • Component path (chuỗi component từ root).
  • Batch ID: biết render nào nằm chung batch.

4.2 UI & State Tab

Tự động phát hiện bốn lỗi thường gặp:

  1. DIRECT_STATE_MUTATION
  2. MISSING_KEY
  3. INDEX_AS_KEY
  4. DUPLICATE_KEY

Mỗi issue card ghi severity, component, snippet, gợi ý fix. Điều này giúp tôi (và cả junior khi tôi review) hiểu pattern đúng.

4.3 Performance Tab

  • Statistic dashboard: số component track, tổng render, average render time (yêu cầu chế độ dev/profiler).
  • Slow renders: top component >16ms, hiển thị max/avg time, render count.
  • Top rerender: ghi rõ trigger reason (props/state/context/parent), changed keys.
  • React Scan overlay: highlight component rerender với màu:
  • xanh lá: 1×
  • vàng: 2-3×
  • cam: 4-5×
  • đỏ cam: 6-10×
  • đỏ: 10+×
  • Page load metrics: FCP, LCP, TTFB, load complete (Core Web Vitals).
  • Performance tips: checklist React.memo, useMemo, useCallback, virtualization.

4.4 Side Effects Tab

Chia issue theo nhóm:

  • Missing cleanup (leak timers, event listener, subscription).
  • Dependency issues (thiếu/thừa dependency).
  • Infinite loop risk (effect setState → rerender → effect).
  • Stale closures (callback dùng state cũ).

Issue card mô tả cụ thể, kèm snippet fix. Tab cũng liệt kê best practice (chia nhỏ effect, dùng useCallback, v.v.).

4.5 CLS Tab

  • Hiển thị current CLS score, rating (good / needs-improvement / poor) với biểu đồ (mốc 0.1, 0.25).
  • Bảng top contributor: selector, total shift, occurrences.
  • Shift timeline: 20 entry mới nhất, tô màu theo severity.
  • Tips: add width/height, aspect-ratio, reserve space, font-display.

4.6 Memory Tab

  • Monitor JS heap: used, total, limit, peak, growth rate, warning.
  • Memory bar gradient 0-100%, highlight 70/90%.
  • Trend chart: polyline used/total.
  • Crash log: JS error, promise rejection, React error, có stack, component stack, memory snapshot, analysis hint.
  • Button Start/Stop monitoring -> gửi message service worker.
  • Tips: cleanup interval, unsubscribe subscription, tránh closure giữ data lớn.

4.7 Redux Tab

  • Detect store qua window.store, window.__REDUX_STORE__, Redux DevTools, Provider context.
  • Action history (timestamp, type) + detail payload.
  • State tree browser: expand/collapse, search, edit inline giá trị (string/number/bool/null/JSON). Hỗ trợ move, delete item trong array.
  • Dispatch action: nhập type + payload JSON.
  • Setup guide khi store chưa expose (tôi đặt cuộn check list “window.store”, “window.REDUX_STORE” …).
  • Khi editing, overlay spinner, highlight “Saving…”.

4.8 Bonus: Test scenarios & tài liệu

README có sẵn test case demo (missing key, excessive render, missing cleanup, layout shift). DEBUGGING-GUIDE.md hơn 600 dòng, kể cả workflow theo cấp độ, metric threshold, keyboard shortcut, color coding.


5. Tôi đo được 60% thời gian debug tiết kiệm như thế nào?

Trong ba sprint gần đây, tôi track 12 bug cụ thể:

  • 5 bug hydration/race effect (trung bình 7 giờ → còn 2,5 giờ).
  • 4 bug rerender/perf (8 giờ → 3 giờ).
  • 3 bug UI/state (4 giờ → 1,5 giờ).

Tiết kiệm khoảng 62%. Điểm mấu chốt:

  1. Tìm root cause nhanh bằng event correlation.
  2. Giảm console.log bừa bãi, giữ PR sạch.
  3. Khi review, tôi đính kèm snapshot JSON timeline, reviewer (hoặc chính tôi một tuần sau) nhìn thấy render reason, diff state → tin tưởng fix, không cần hỏi thêm.

6. Best practice tôi đang áp dụng với React Debugger

  1. Chụp snapshot trước & sau khi tối ưu để so sánh render order, changed key.
  2. Dùng React Scan thay vì đoán: overlay highlight component rerender theo màu, không tranh luận theo cảm tính.
  3. Theo dõi Memory trong thời gian dài: start monitoring trước khi chạy stress test 10-15 phút để xem growth rate.
  4. Bookmark issue: trong UI & State tab, tôi đánh dấu, ghi chú TODO cá nhân.
  5. Kết hợp với QA: QA dùng CLS tab check layout shift, gửi log thẳng cho tôi.
  6. Workflow theo cấp độ (tôi viết trong DEBUGGING-GUIDE):
  • Fresher: tập trung UI & State + Side Effects.
  • Mid-level: Performance + Timeline + Memory.
  • Senior (hoặc chính tôi khi đóng vai tech lead): dùng tất cả, kết hợp correlation, ra quyết định kiến trúc.
  1. Expose Redux store ở dev mode: if (process.env.NODE_ENV === 'development') window.store = store; để Redux tab hoạt động tối ưu.

7. Tính minh bạch & độ tin cậy cá nhân tôi cam kết

  • Open-source MIT: Repo public, ai cũng audit. Tôi ghi rõ license MIT, khuyến khích đóng góp.
  • Tài liệu đầy đủ: README, DEBUGGING-GUIDE.md trên 600 dòng (tab, metric, workflow).
  • Test scenario: README cung cấp demo component, QA copy/paste ngay.
  • Theo chuẩn web: FCP/LCP/TTFB và threshold CLS theo Google Web Vitals.
  • Kiến trúc: Background script + content script tách biệt, manifest V3.
  • Triết lý: Không suppress type error, khuyến khích best practice, đo lường trước khi tối ưu.
  • Sử dụng thực tế: Tôi dùng extension này mỗi ngày, mọi feedback tôi ghi lại thành issue/PR công khai.

8. Roadmap & lời hứa cá nhân

Tôi không dừng lại ở v1.0.0. Những việc đang nằm trong backlog cá nhân:

  1. Hỗ trợ React Server Components sâu hơn – track boundary server/client.
  2. Plugin rule tùy chỉnh – cho phép define company guideline (ví dụ: cảnh báo useLayoutEffect trong SSR).
  3. Session Replay nhẹ – export timeline + screenshot nhỏ.
  4. CI Integration – CLI so sánh snapshot, nhúng báo cáo vào PR.
  5. Telemetry tùy chọn – nếu người dùng bật, gửi thống kê ẩn danh để ưu tiên feature.
  6. Tài liệu tiếng Việt đầy đủ hơn – hỗ trợ cộng đồng React Việt.

Tôi cam kết: số hóa changelog rõ ràng, lắng nghe issue từ GitHub/Discord, và ưu tiên tiện ích thực tế. Tôi không muốn extension trở thành gánh nặng – nó phải là bạn đồng hành.


9. Kết lại – đừng để debugging “đánh cắp” tình yêu lập trình của chính bạn

Debug React có lẽ sẽ không bao giờ trở thành thú vui nhẹ nhàng. Nhưng tôi đã học cách biến nó thành nhiệm vụ có bản đồ, đèn pin và lối thoát rõ ràng. React Debugger giúp tôi:

  • Thay vì spam console.log, tôi nhìn vào timeline và hiểu chuỗi sự kiện.
  • Biết component nào rerender và vì sao.
  • Chuẩn hóa review (đính kèm snapshot, issue card).
  • Tự tin fix bug ngay cả trong bản demo live.
  • Giữ tinh thần ổn định sau nhiều giờ debugging.

Nếu bạn từng cảm thấy “React thực sự ghét mình”, hãy thử mở React Debugger, lướt qua từng tab. Bạn sẽ thấy câu chuyện mà ứng dụng của mình muốn nói – rõ ràng hơn, ít drama hơn, và quan trọng nhất: tiết kiệm thời gian để xây tính năng mới.

React Debugger không phải cây đũa thần, nhưng nó là chiếc kính hiển vi giúp tôi nhìn ra điều mắt thường bỏ lỡ. Và khi tôi tiếp tục đẩy những cập nhật mới, tôi luôn nhớ rằng: mình vẫn đang lăn tảng đá mỗi ngày, nhưng lần này có một công cụ đáng tin cậy đồng hành, để con đường phía trước bớt dốc hơn.

The post Từ Bế Tắc Debugging Đến Kiểm Soát Hoàn Toàn: Hành Trình Xây Dựng React Debugger Extension appeared first on Th?nk And Grow.

]]>
Stop Using != deleted_at: Database Soft Delete Performance Guide https://blog.thnkandgrow.com/stop-using-deleted_at-database-soft-delete-performance-guide/ Fri, 09 Jan 2026 00:22:10 +0000 https://blog.thnkandgrow.com/?p=2657 In the world of massive applications, "deleting" data is rarely simple. We almost never actually delete rows (DELETE FROM table). Instead, we use "Soft Deletes"—marking a row as deleted so it can be restored or audited later. The two most common ways to do this are: The Boolean: is_deleted = true The Timestamp: deleted_at = […]

The post Stop Using != deleted_at: Database Soft Delete Performance Guide appeared first on Th?nk And Grow.

]]>
Stop Using != deleted_at: Database Soft Delete Performance Guide

In the world of massive applications, "deleting" data is rarely simple. We almost never actually delete rows (DELETE FROM table). Instead, we use "Soft Deletes"—marking a row as deleted so it can be restored or audited later.

The two most common ways to do this are:

  1. The Boolean: is_deleted = true
  2. The Timestamp: deleted_at = '2024-01-01 12:00:00'

Developers often prefer the Timestamp approach because it gives you when it happened. But there is a massive hidden cost that bites you when your table hits 100 million or 1 billion rows.

And it usually starts with a query like this:

SELECT * FROM users WHERE deleted_at != NULL;

Here is why that query—and the deleted_at column itself—might be killing your database performance, and how to fix it properly.

The Logic Trap: Inequality (!=) vs Indexes

The first performance killer is how you query it. It is very common to see ORMs or developers query for "deleted items" using inequality operators:

-- "Show me all deleted users"
SELECT * FROM users WHERE deleted_at != NULL;
-- OR
SELECT * FROM users WHERE deleted_at IS NOT NULL;

Why this hurts

Equality vs Inequality Lookup Performance

Database B-Tree indexes are optimized for equality (=) and sorted ranges (>, <). They are essentially sorted lists.

When you ask for deleted_at IS NOT NULL, you are essentially asking the database to "give me everything that has a value." If your table has 1 billion rows, and 10% are deleted (100 million rows), the database has to scan a massive portion of the index.

Worse, standard B-Tree indexes in some databases (like older Oracle versions, though less true for modern Postgres/MySQL) handled NULLs poorly. But even with modern handling, Inequality is expensive.

The Cardinality Problem

Performance isn't just about the operator; it's about Cardinality (how unique the data is).

The Scenario

Billion Row Table Schematic View

Imagine a files table with 1 Billion rows.

  • 99% are Active (deleted_at is NULL).
  • 1% are Deleted (deleted_at has a timestamp).

If you index deleted_at: CREATE INDEX idx_deleted_at ON files(deleted_at);

You are creating a massive index containing 1 Billion entries.

  • 990 Million entries look identical (NULL), or are stored as a massive group.
  • 10 Million entries have timestamps.

Querying for Active Rows

When you run SELECT * FROM files WHERE deleted_at IS NULL: The database looks at the index. It sees that 99% of the index references the rows you want. It will likely ignore the index entirely. Why? Because reading the index and then fetching 99% of the table rows is slower than just doing a Full Table Scan and ignoring the index from the start.

Result: You paid the storage cost for a 1-Billion-row index, and your database doesn't even use it for your most common query.

The Solution: Indexing What Matters

We want two things:

  1. Fast lookups for active records (99% of queries).
  2. Small index size (RAM is expensive).

1. The Low-Tech Win: is_deleted (Boolean)

Using is_deleted (boolean/tinyint) is slightly better because the data type is tiny (1 byte vs 8 bytes for timestamp). However, it suffers the same Cardinality problem. An index on is_deleted where 99% of values are FALSE is useless for finding active records.

2. The High-Tech Win: Partial Indexes (PostgreSQL)

This is the "Silver Bullet" for PostgreSQL users. PostgreSQL allows you to create Partial Indexes—indexes that only contain rows that match a WHERE clause.

-- Only index the rows that are NOT deleted
CREATE INDEX idx_files_active
ON files (user_id, created_at)
WHERE deleted_at IS NULL;
PostgreSQL Partial Indexes Diagram

Why this is genius:

  1. Size: If 99% of your data is active, the index is still large. BUT, if you flip it—say you archive data often and only 20% is active—your index is tiny.
  2. Uniqueness: You can enforce uniqueness only on active items.
     -- Allow soft-deleted duplicates, but unique active emails
    CREATE UNIQUE INDEX idx_unique_email
    ON users(email)
    WHERE deleted_at IS NULL;
    
  3. Speed: The index for filtered queries is smaller, fits in RAM, and is faster to scan.

Wait, what if I have 99% active data? If 99% of data is active, a partial index WHERE deleted_at IS NULL is still huge (99% size). In this specific case (Billions of active rows), you generally do not index the soft-delete column alone. You include it in Composite Indexes.

-- MySQL / Postgres
CREATE INDEX idx_user_active_files
ON files (user_id, deleted_at);

When you query WHERE user_id = 123 AND deleted_at IS NULL, the database jumps to user 123 and indexes allow instant filtering of the NULLs.

What about MySQL?

MySQL (before 8.0) did not support true Partial Indexes. MySQL 8.0+ supports "Invisible Columns" or "Functional Key Parts" which can simulate this, but it's trickier.

Best Practice for MySQL: Use a composite index. Put deleted_at (or is_deleted) last in your index if you query for exact matches on other columns.

-- Good
CREATE INDEX idx_user_status ON users (company_id, is_deleted);

Summary Recommendation

  1. Don't use != or <> if you can help it. Use positive assertions (IS NULL or = 0).
  2. Stop indexing deleted_at by itself if >10% of your data is active. It's a wasted index usually.
  3. Use PostgreSQL Partial Indexes (WHERE deleted_at IS NULL) if you need to enforce unique constraints on active data.
  4. Use Composite Indexes (user_id, deleted_at) for standard filtering.

If you are hitting 1 Billion rows, every byte in your index counts. Don't index the garbage you threw in the trash.

The post Stop Using != deleted_at: Database Soft Delete Performance Guide appeared first on Th?nk And Grow.

]]>