Course contentsShow
← TypeScript
Lesson 1566 of 1,79636. tRPC and End-to-End Type SafetyFree lesson

Idempotency and Query vs Mutation Choice

Learn why idempotent operations should be queries and how this affects caching and safety.

Idempotency and Query vs Mutation Choice

What you'll learn: How idempotent operations should be queries and how this affects caching and safety in tRPC applications.

The Core Concept

Idempotency means an operation can be performed multiple times with the same result. In HTTP terms, think of GET requests: reading the same article ten times doesn't change the article. This property has profound implications for how you should choose between tRPC's query() and mutation() methods.

The key principle: idempotent operations should be queries, non-idempotent operations should be mutations.

Why This Matters

When you mark a procedure as a query, tRPC clients assume it's safe to:

  • Cache the result aggressively
  • Retry automatically on failure
  • Re-fetch in the background
  • Call it multiple times without side effects

When you mark a procedure as a mutation, clients treat it as:

  • Non-cacheable
  • Only executed when explicitly called
  • Potentially dangerous to retry
  • State-changing

The Decision Framework

Use query() when:

  • Fetching data without changing anything
  • The same input always returns the same result (at that moment)
  • It's safe to call multiple times
  • Examples: getting a user profile, listing products, reading settings

Use mutation() when:

  • Creating, updating, or deleting resources
  • Sending emails or notifications
  • Processing payments
  • Any operation where running it twice produces different outcomes
  • Examples: creating an order, updating a password, charging a credit card

The Caching Consequence

If you mistakenly use query() for a non-idempotent operation like creating a user, the client might cache that "success" response. The next time the form is submitted, instead of creating another user, the cached result is returned—and nothing happens server-side. This is a serious bug.

Conversely, using mutation() for a simple data fetch means you lose automatic caching, background refetching, and optimistic updates—sacrificing developer experience and performance for no safety gain.

Key Takeaway: Choose query() for idempotent, read-only operations to enable caching and safe retries; choose mutation() for state-changing operations to prevent unintended side effects and ensure explicit execution control.