Fixing Claude Code EACCES: Multi-User Linux Permission Architecture

When you’re running Claude Code across multiple Linux user accounts and hit EACCES: permission denied, the solution isn’t just chmod 777. This is the complete troubleshooting journey from error to production-ready multi-user architecture.

The Problem: Two Users, One Claude Code Instance

Initial symptom: User jeremy couldn’t start Claude Code:

EACCES: permission denied, open
syscall: "open",
  errno: -13,
   code: "EACCES"

Context:

  • Two user accounts: jeremy (master) and admincostplus (admin)
  • Both need to run Claude Code independently
  • Shared configuration desired (plugins, MCP servers, slash commands)
  • No permission conflicts or ownership battles

The naive approach? “Just give both users access.” The correct approach? Architect a system that scales.

Phase 1: Understanding the Problem (What We Discovered)

Investigation Started with Basic Checks

# Check current user and home
whoami  # admincostplus
ls -la ~/.claude  # Owned by admincostplus, 700 permissions

# Try to identify what's failing
claude --dangerously-skip-permissions
# Still fails with EACCES on file open

Key discovery: The error wasn’t about running Claude Code—it was about Claude Code trying to write logs and configuration files to directories it couldn’t access.

The Ownership Mess We Found

# Jeremy's directory had files owned by the wrong user
ls -la /home/jeremy/.claude/debug/
drwx------ 2 admincostplus admincostplus 12288 Oct 23 14:21 debug

# This meant:
# - admincostplus had created files in jeremy's home directory earlier
# - jeremy (the owner) couldn't write to his own .claude/debug directory
# - Claude Code failed when trying to append to log files

Why this happened: Earlier troubleshooting attempts ran Claude Code as admincostplus, which created directories and files in shared locations with the wrong ownership.

Phase 2: The Architecture (What Actually Works)

The solution uses three layers of Linux permissions magic:

  1. Shared directory with setgid bit – All files inherit group ownership
  2. Symlinks for admin user – Transparent redirection to shared location
  3. Real directories for master user – Jeremy keeps his own independent copy

The Complete Script

Here’s the production script. Run it as root or with sudo:

#!/bin/bash
# Multi-user Claude Code configuration
# Run as: sudo bash this-script.sh

# Variables
MASTER_USER=jeremy
ADMIN_USER=admincostplus
SHARED=/opt/claude-shared
GROUP=claudeusers
MASTER_HOME=$(getent passwd "$MASTER_USER" | cut -d: -f6)
ADMIN_HOME=$(getent passwd "$ADMIN_USER" | cut -d: -f6)
DIRS=(".claude" ".claude-code" ".config/claude-code" ".local/share/claude-code")

# 1) Create group and add both users
getent group "$GROUP" >/dev/null || groupadd "$GROUP"
usermod -a -G "$GROUP" "$MASTER_USER"
usermod -a -G "$GROUP" "$ADMIN_USER"

# 2) Create shared directory and seed from master user
mkdir -p "$SHARED"
chown -R "$MASTER_USER:$GROUP" "$SHARED"
chmod 2775 "$SHARED"  # setgid bit ensures group inheritance

for rel in "${DIRS[@]}"; do
  src="$MASTER_HOME/$rel"
  dst="$SHARED/$rel"
  mkdir -p "$(dirname "$dst")"

  if [ -d "$src" ]; then
    rsync -a --delete "$src"/ "$dst"/
  else
    mkdir -p "$dst"
  fi
done

# 3) Replace admin's real directories with symlinks
for rel in "${DIRS[@]}"; do
  link="$ADMIN_HOME/$rel"
  target="$SHARED/$rel"

  # Backup existing directory if it's not already a symlink
  [ -e "$link" ] && [ ! -L "$link" ] && 
    mv "$link" "$link.bak-$(date +%Y%m%d-%H%M%S)"

  mkdir -p "$(dirname "$link")"
  rm -rf "$link"
  ln -s "$target" "$link"
done

# 4) Set group permissions with setgid on all directories
chown -R "$MASTER_USER:$GROUP" "$SHARED"
chmod -R g+rX "$SHARED"
find "$SHARED" -type d -exec chmod 2775 {} +

# 5) Optional: Set ACLs for belt-and-suspenders approach
command -v setfacl >/dev/null && 
  setfacl -R -m g:$GROUP:rwx -m d:g:$GROUP:rwx "$SHARED" || true

# 6) Environment variable for admin user only
cat >/etc/profile.d/claude-code-admin.sh <<'EOF'
[ "$USER" = "admincostplus" ] && export CLAUDE_CODE_HOME="/opt/claude-shared/.claude-code"
EOF
chmod 644 /etc/profile.d/claude-code-admin.sh

# 7) Kill any stale processes
pkill -f 'claude|node .*claude' || true

echo "✅ Multi-user Claude Code setup complete"
echo "   Master user: $MASTER_USER (uses real directories)"
echo "   Admin user: $ADMIN_USER (uses symlinks to shared)"

Why This Architecture Works

For admincostplus (admin user):

  • Symlinks redirect all Claude Code file operations to /opt/claude-shared
  • Writes go to shared location where group permissions grant access
  • Transparent to Claude Code—it doesn’t know it’s writing to shared storage

For jeremy (master user):

  • Uses real directories at /home/jeremy/.claude
  • Full ownership and control
  • Changes sync to shared directory (manual rsync when needed)

The setgid bit (2775):

chmod 2775 /opt/claude-shared
# The '2' is the setgid bit
# Effect: All new files/directories inherit the group 'claudeusers'
# Result: No ownership conflicts when both users write

Phase 3: The Critical Bug We Hit

After running the script, Jeremy still got EACCES errors. Why?

Debugging the “It Should Work But Doesn’t” Moment

# Check symlinks - ✅ Correct
ls -la /home/admincostplus/.claude
lrwxrwxrwx 1 root root 26 Oct 23 14:33 .claude -> /opt/claude-shared/.claude

# Check group membership - ✅ Correct
id jeremy
groups=1001(admincostplus),27(sudo),1000(jeremy),1002(claudeusers)

# Check permissions on shared - ✅ Correct
ls -ld /opt/claude-shared/.claude
drwxrwsr-x 13 jeremy claudeusers 4096 Oct 23 14:35 .

# Test write to shared - ✅ Works
sudo -iu admincostplus bash -lc 'touch ~/.claude/debug/test.txt'
# Success!

Everything looked perfect. So why did Claude Code still fail for Jeremy?

The Real Problem: Ownership Pollution

# Check Jeremy's actual .claude directory
ls -la /home/jeremy/.claude/debug/
drwx------ 2 admincostplus admincostplus 12288 Oct 23 14:21 debug

# ❌ Jeremy's own directory was owned by admincostplus!
# Jeremy couldn't write to his own home directory

Root cause: During earlier troubleshooting, admincostplus had run commands that created files in Jeremy’s home directory. Those files retained admincostplus ownership.

The Fix

# Reclaim ownership of Jeremy's directories
sudo chown -R jeremy:jeremy /home/jeremy/.claude
sudo chown -R jeremy:jeremy /home/jeremy/.claude-code
sudo chown -R jeremy:jeremy /home/jeremy/.config/claude
sudo chown -R jeremy:jeremy /home/jeremy/.local/share/claude-code

# Fix permissions
sudo chmod 755 /home/jeremy/.claude

Critical lesson: In multi-user debugging, always check ownership of the actual directories, not just the symlinks and shared locations.

Phase 4: The Environment Variable Bug

After fixing ownership, we found the CLAUDE_CODE_HOME environment variable wasn’t being set.

The Escaping Issue

# What the script wrote (WRONG):
cat /etc/profile.d/claude-code-admin.sh
[ "$USER" = "admincostplus" ] && export CLAUDE_CODE_HOME="/opt/claude-shared/.claude-code"
#  ^^^ Escaped dollar sign prevents variable expansion

# Testing confirmed it didn't work:
sudo -iu admincostplus bash -lc 'echo $CLAUDE_CODE_HOME'
# (empty output)

The Fix

# Use double quotes with escaped backslash for heredoc
cat >/etc/profile.d/claude-code-admin.sh <<'EOF'
[ "$USER" = "admincostplus" ] && export CLAUDE_CODE_HOME="/opt/claude-shared/.claude-code"
EOF

# Or use echo with proper escaping:
echo '[ "$USER" = "admincostplus" ] && export CLAUDE_CODE_HOME="/opt/claude-shared/.claude-code"' 
  | sudo tee /etc/profile.d/claude-code-admin.sh

# Verify it works:
sudo -iu admincostplus bash -lc 'echo $CLAUDE_CODE_HOME'
/opt/claude-shared/.claude-code  # ✅ Success

Phase 5: Verification (How to Know It Actually Works)

Comprehensive Smoke Tests

# Test 1: Verify symlinks resolve correctly
sudo -iu admincostplus bash -lc 'readlink -f ~/.claude'
/opt/claude-shared/.claude  # ✅

# Test 2: Verify Jeremy uses real directories
sudo -iu jeremy bash -lc 'readlink -f ~/.claude || echo "Real directory"'
/home/jeremy/.claude  # ✅

# Test 3: Write permissions for admincostplus
sudo -iu admincostplus bash -lc 'touch ~/.claude/test.txt && rm ~/.claude/test.txt'
# ✅ Success

# Test 4: Write permissions for jeremy
sudo -iu jeremy bash -lc 'touch ~/.claude/test.txt && rm ~/.claude/test.txt'
# ✅ Success

# Test 5: Claude Code runs for both users
sudo -iu jeremy bash -lc 'claude --version'
2.0.25 (Claude Code)  # ✅

sudo -iu admincostplus bash -lc 'claude --version'
2.0.8 (Claude Code)  # ✅

# Test 6: Environment variable is set
sudo -iu admincostplus bash -lc 'echo $CLAUDE_CODE_HOME'
/opt/claude-shared/.claude-code  # ✅

What Success Looks Like

For admincostplus:

$ whoami
admincostplus

$ ls -la ~/.claude
lrwxrwxrwx 1 root root 26 Oct 23 14:33 .claude -> /opt/claude-shared/.claude

$ claude --version
2.0.8 (Claude Code)

$ echo $CLAUDE_CODE_HOME
/opt/claude-shared/.claude-code

For jeremy:

$ whoami
jeremy

$ ls -la ~/.claude
drwxr-xr-x 13 jeremy jeremy 4096 Oct 23 14:35 .claude

$ claude --version
2.0.25 (Claude Code)

$ echo $CLAUDE_CODE_HOME
(empty - uses default ~/.claude-code)

Key Lessons from This Debugging Journey

1. EACCES Doesn’t Mean “Wrong Permissions”

It means “wrong ownership, wrong permissions, wrong user, wrong directory, or wrong architecture.” You have to investigate systematically:

  • Check file ownership: ls -la
  • Check group membership: id username
  • Check directory permissions: stat -c "%U:%G %a" /path
  • Check what’s failing: Read the actual system call in the error

2. The Setgid Bit Is Your Friend

chmod 2775 /opt/claude-shared
# This bit (2) makes all new files inherit the directory's group
# Without it, files created by different users have different groups
# With it, all files in the directory get the same group ownership

3. Symlinks Are Transparent Permission Redirects

When you symlink ~/.claude → /opt/claude-shared/.claude:

  • All file operations follow the symlink
  • Permissions are checked at the target location
  • The source link doesn’t need special permissions (just read/traverse)

4. Test Each Layer Independently

Don’t assume the script worked. Verify:

  1. Group exists and users are members: getent group claudeusers
  2. Shared directory has correct ownership: ls -ld /opt/claude-shared
  3. Symlinks point to correct targets: readlink -f ~/.claude
  4. Both users can write: touch ~/.claude/test.txt
  5. Environment variables are set: echo $CLAUDE_CODE_HOME
  6. Application runs: claude --version

5. Ownership Pollution Is Silent and Deadly

During debugging, running commands as different users can leave landmines:

# This creates files owned by admincostplus in jeremy's home
sudo -u admincostplus touch /home/jeremy/.claude/test.txt

# Later, jeremy can't delete or modify them
# The solution: Always clean up after debugging
sudo chown -R jeremy:jeremy /home/jeremy/

Production Checklist

Before deploying this architecture:

  • [ ] Backup existing .claude directories for both users
  • [ ] Create the claudeusers group and add members
  • [ ] Test write access with touch commands before running Claude Code
  • [ ] Verify symlinks are correct with readlink -f
  • [ ] Check environment variables are set with echo $VAR
  • [ ] Kill existing Claude Code processes before testing
  • [ ] Test Claude Code runs successfully for both users
  • [ ] Document which user is “master” (owns shared directory)
  • [ ] Set up a sync script if master user makes changes
  • [ ] Add monitoring for permission drift over time

Related Reading

The Result

Two users, zero permission conflicts, shared configuration, independent Claude Code instances. This pattern scales to any number of users—just add them to the claudeusers group and create symlinks.

Before: EACCES errors, manual permission fixes, confusion about ownership.

After: Transparent multi-user access, automatic group inheritance, architectural clarity.

The difference between “just make it work” and “make it work correctly” is architecture. This is the latter.

Senior Developer Interview Checklist: System Design, Algorithms & Behavioral

Senior developer interviews are different in kind, not just difficulty. Mid-level interviews test what you know. Senior interviews test how you think. This checklist is built around that distinction — covering not just topics to study, but how to approach each area with the depth interviewers are actually looking for.

The Senior Engineer Mindset

Before the checklist, understand what “senior” signals to an interviewer. The shift from mid to senior isn’t primarily about technical knowledge — it’s about:

  • Judgment under ambiguity — making good decisions with incomplete information
  • Communication clarity — explaining complex systems to different audiences
  • Tradeoff awareness — articulating why you chose X over Y, not just that you chose X
  • Scope awareness — knowing when a problem needs a simple fix vs. a systemic solution

Every interview section below should be approached through this lens.

Part 1: System Design

System design is the primary differentiator in senior interviews. The goal isn’t to produce a perfect architecture — it’s to demonstrate structured thinking.

The Framework to Follow

For every system design question, use this structure:

  1. Clarify requirements (5 min)

    • Functional requirements: what does the system do?
    • Non-functional: scale, latency, consistency requirements, availability?
    • Scope: what’s in scope for this interview?
  2. Estimate scale (5 min)

    • Daily active users
    • Read/write ratio
    • Data volume (storage needs)
    • Traffic patterns (uniform or bursty?)
  3. High-level design (15 min)

    • Draw the major components: clients, load balancers, servers, databases, caches
    • Identify the data flow for the core use cases
  4. Deep dive (15 min)

    • Pick 1-2 components the interviewer cares about most
    • Discuss tradeoffs in your choices
  5. Bottlenecks and scaling (5 min)

    • What breaks first at 10x scale?
    • How would you handle it?

Core System Design Topics to Master

Databases:

  • [ ] SQL vs NoSQL — when to use each, not just what they are
  • [ ] Database indexing — B-tree vs hash indexes, composite indexes, covering indexes
  • [ ] Replication — primary-replica, multi-primary, consistency tradeoffs
  • [ ] Sharding — horizontal partitioning strategies, hotspot problems
  • [ ] CAP theorem — understand the practical implications, not just the theory

Caching:

  • [ ] Cache invalidation strategies — TTL, event-driven, write-through vs write-back
  • [ ] Cache eviction — LRU, LFU, when each makes sense
  • [ ] CDN caching vs application caching vs database query caching
  • [ ] Redis data structures beyond key-value (sorted sets for leaderboards, pub/sub for events)

Distributed Systems:

  • [ ] Consistent hashing — how it distributes load, why it minimizes remapping
  • [ ] Distributed transactions — two-phase commit, saga pattern, eventual consistency
  • [ ] Message queues — Kafka vs RabbitMQ, when to use async over sync
  • [ ] Rate limiting — token bucket vs leaky bucket, where to enforce it

APIs and Communication:

  • [ ] REST design — resource modeling, idempotency, versioning strategies
  • [ ] GraphQL — when it’s better than REST, N+1 problem, DataLoader pattern
  • [ ] gRPC — when low latency or streaming matters
  • [ ] WebSockets vs SSE — real-time use cases and tradeoffs

Common System Design Questions:

  • Design a URL shortener (covers hashing, databases, caching, scale)
  • Design a notification system (covers queuing, fan-out, delivery guarantees)
  • Design a rate limiter (covers distributed state, consistency, efficiency)
  • Design a news feed / timeline (covers fan-out on read vs write, caching)
  • Design a distributed cache like Redis (covers consistency, eviction, clustering)

System Design Red Flags to Avoid

  • Jumping to a solution without clarifying requirements
  • Single points of failure with no discussion of resilience
  • No mention of failure modes (“what happens when service X goes down?”)
  • Scale numbers that don’t add up (back-of-napkin math should be consistent)
  • Choosing technologies without explaining why

Part 2: Algorithms and Data Structures

Senior engineers are not expected to solve LeetCode Hard in 15 minutes under pressure. They are expected to think through problems systematically, communicate their approach, and produce correct, efficient solutions.

Algorithmic Foundations

Must-know patterns:

  • [ ] Two pointers — array problems, palindrome detection, sorted array merging
  • [ ] Sliding window — substring problems, max subarray, fixed-size window stats
  • [ ] Binary search — not just sorted arrays; search space reduction on any monotonic function
  • [ ] BFS/DFS — tree traversal, graph connectivity, shortest path (BFS), cycle detection
  • [ ] Dynamic programming — bottom-up vs top-down, identifying subproblem structure
  • [ ] Heap / priority queue — top-K problems, merge K sorted lists, scheduling
  • [ ] Hash maps — frequency counting, two-sum pattern, grouping

Data structures to know deeply:

  • [ ] Arrays and strings — in-place operations, rotation, sliding window
  • [ ] Linked lists — reversal, cycle detection (Floyd’s), merge
  • [ ] Trees — BST operations, LCA, path sum, level-order traversal
  • [ ] Graphs — adjacency list vs matrix, Dijkstra’s algorithm, union-find
  • [ ] Stacks and queues — monotonic stack, queue using stacks

How to Approach Coding Problems in Interviews

1. Repeat the problem back in your own words
2. Work through 1-2 examples by hand
3. State the naive solution first ("The O(n²) solution would be...")
4. Identify the optimization ("We can do better by...")
5. Code it
6. Test with your examples + edge cases
7. Analyze time/space complexity

The narration matters as much as the code. Interviewers can’t see inside your head.

Complexity You Should Know Cold

Operation Data Structure Time
Access by index Array O(1)
Insert/delete at front Linked List O(1)
Search Hash Map O(1) avg
Insert/delete Balanced BST O(log n)
Insert / Extract min Min Heap O(log n)
Sort Array O(n log n)
BFS/DFS Graph (V+E) O(V+E)

Part 3: Behavioral Interviews

Senior behavioral interviews dig into leadership, judgment, and conflict — not just “tell me about a project.” The STAR format (Situation, Task, Action, Result) is the baseline, but senior interviews push harder on the “why.”

Categories to Prepare Stories For

Technical leadership:

  • [ ] A time you made a significant architectural decision — what was the tradeoff, who did you align with?
  • [ ] A time you pushed back on a technical direction — how did you frame it, what happened?
  • [ ] A time you simplified a system or removed complexity — why was it needed?

Handling failure:

  • [ ] A production incident you were responsible for — what happened, how did you respond, what changed after?
  • [ ] A project that failed or was cancelled — what did you learn, what would you do differently?
  • [ ] A technical debt situation you had to navigate

Collaboration and influence:

  • [ ] A time you disagreed with your manager or a senior stakeholder — how did you handle it?
  • [ ] A time you mentored someone — what did you focus on, how did it go?
  • [ ] A time you drove alignment across teams with conflicting priorities

Estimation and planning:

  • [ ] A time your estimate was wrong — what happened, how did you communicate it?
  • [ ] A time you had to scope down a project under deadline pressure — how did you decide what to cut?

Strong STAR Story Structure for Senior Roles

Weak answer: “I noticed a performance problem, I fixed it, the site got faster.”

Strong answer:

  • Situation: What was the business context? (Users were churning at a specific step, alerting was showing p99 latency over 3s)
  • Task: What was your specific responsibility? (I owned the checkout service, this was my problem to solve)
  • Action: What did you do — including the hard parts? (I profiled, found N+1 queries, proposed a solution, got pushback on timeline, negotiated a phased approach, implemented it over 2 sprints)
  • Result: Quantified outcome + what you’d do differently (p99 dropped from 3.1s to 340ms, checkout conversion +4%, in retrospect I should have added monitoring before the fix to baseline properly)

The “what I’d do differently” signals senior self-awareness.

Part 4: Code Review and Engineering Practices

Many senior interviews include a code review exercise — reading existing code and identifying issues. This tests your real-world judgment more than whiteboard algorithms.

What to Look For in Code Reviews

Correctness:

  • [ ] Off-by-one errors
  • [ ] Null/undefined handling
  • [ ] Edge cases (empty input, single element, maximum values)
  • [ ] Race conditions in concurrent code

Security:

  • [ ] SQL injection (string concatenation in queries)
  • [ ] XSS (unescaped user input rendered as HTML)
  • [ ] Hardcoded credentials
  • [ ] Missing input validation at API boundaries

Performance:

  • [ ] N+1 queries (fetching in a loop that could be one query)
  • [ ] Missing database indexes for query patterns
  • [ ] Unnecessary computation inside loops
  • [ ] Memory leaks (event listeners not cleaned up)

Maintainability:

  • [ ] Functions doing more than one thing
  • [ ] Magic numbers without named constants
  • [ ] Missing error handling
  • [ ] Test coverage for critical paths

Part 5: Domain-Specific Topics

Depending on the role, expect depth in one of these areas:

Frontend Senior

  • [ ] Browser rendering pipeline — critical rendering path, layout vs paint vs composite
  • [ ] Performance — Core Web Vitals (LCP, FID/INP, CLS), bundle analysis, code splitting
  • [ ] Accessibility — WCAG 2.1 AA, ARIA roles, keyboard navigation, screen reader testing
  • [ ] State management — when to use context vs external store, avoiding prop drilling
  • [ ] TypeScript — advanced types, generics, utility types, discriminated unions

Backend Senior

  • [ ] Database query optimization — EXPLAIN ANALYZE, index design, query rewriting
  • [ ] API design — idempotency, versioning, backward compatibility
  • [ ] Security — OWASP Top 10, authentication vs authorization, secrets management
  • [ ] Observability — structured logging, metrics, tracing, alert design
  • [ ] Containerization — Docker multi-stage builds, orchestration basics

Full-Stack Senior

  • [ ] Auth patterns — session vs JWT, OAuth 2.0 / OIDC flows, refresh token rotation
  • [ ] Deployment — CI/CD pipelines, blue-green deploys, feature flags, rollbacks
  • [ ] Monitoring — defining SLOs, alerting on symptoms vs causes

Interview Week Checklist

One week before:

  • [ ] Review 2-3 system design problems end-to-end
  • [ ] Practice coding one problem per day (medium difficulty, focus on communication)
  • [ ] Prepare 6-8 STAR stories covering the behavioral categories above
  • [ ] Research the company’s tech stack and any recent engineering blog posts

Day before:

  • [ ] Light review, no new material
  • [ ] Prepare your setup: quiet space, reliable internet, IDE ready
  • [ ] Have a glass of water and something to write on

During interviews:

  • [ ] Ask clarifying questions before you start
  • [ ] Narrate your thinking out loud
  • [ ] Name tradeoffs explicitly (“The downside of this approach is…”)
  • [ ] Ask for feedback at the end (“Is there a direction you’d have taken this instead?”)

The most honest advice: Senior interviews reward people who’ve thought deeply about their own work. The preparation that matters most isn’t grinding LeetCode — it’s being able to articulate why you made the choices you made in your career, what broke, what you’d do differently, and what you’re still figuring out.

Level Up Your Dev Workflow

Found this useful? Explore DevPlaybook — cheat sheets, tool comparisons, and hands-on guides for modern developers.

🛒 Get the DevToolkit Starter Kit on Gumroad — 40+ browser-based dev tools, source code + deployment guide included.

Understanding REST API Design Best Practices

A REST API is a contract. Every decision you make when designing it — URL structure, status codes, error formats, versioning — becomes a constraint your consumers must work around. Get it right upfront, and integration is smooth. Get it wrong, and you’ll be maintaining backwards-compatibility hacks for years.

Here’s what separates a well-designed REST API from a frustrating one.

Think in Resources, Not Actions

REST is resource-oriented. URLs identify things, HTTP methods express what you’re doing to them.

# Wrong — action-based URLs
POST /createUser
GET  /getUserById?id=42
POST /deleteUser
POST /updateUserEmail

# Right — resource-based URLs
POST   /users          # create a user
GET    /users/42       # get a specific user
DELETE /users/42       # delete a user
PATCH  /users/42       # partially update a user

The HTTP method carries the semantic meaning. Your URL should only identify what resource is being acted on.

Nested Resources

Use nesting for resources that belong to a parent:

GET  /users/42/orders         # all orders for user 42
GET  /users/42/orders/7       # specific order
POST /users/42/orders         # create order for user 42

Limit nesting to one or two levels deep. Beyond that, use query parameters or flat resource paths.

HTTP Methods: Use Them Correctly

Each HTTP method carries a specific meaning that clients and infrastructure depend on.

Method Semantics Safe Idempotent
GET Read Yes Yes
POST Create No No
PUT Full replace No Yes
PATCH Partial update No No
DELETE Delete No Yes

Safe means the request doesn’t modify state — caches and intermediaries can call it freely.

Idempotent means calling it multiple times produces the same result — important for retries on network failure.

# PUT should fully replace the resource
PUT /users/42
{ "name": "Alice Smith", "email": "[email protected]", "role": "admin" }

# PATCH updates only the fields provided
PATCH /users/42
{ "email": "[email protected]" }

Status Codes: Say What You Mean

HTTP status codes are a semantic protocol. Using them correctly means clients can handle responses without parsing error messages.

Success (2xx)

200 OK          — general success (GET, PUT, PATCH)
201 Created     — resource was created (POST), include Location header
204 No Content  — success with no body (DELETE)

Client Errors (4xx)

400 Bad Request      — invalid input, validation failure
401 Unauthorized     — not authenticated (missing/invalid token)
403 Forbidden        — authenticated but not permitted
404 Not Found        — resource doesn't exist
409 Conflict         — state conflict (duplicate key, version mismatch)
422 Unprocessable    — valid format but semantic errors (can't process)
429 Too Many Requests — rate limited

The most common mistake: returning 200 OK with an error in the body. That makes every client parse the response body just to check if the request succeeded.

Consistent Error Responses

Define a standard error format and use it everywhere:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Email address is invalid",
    "field": "email",
    "requestId": "req_abc123"
  }
}

Key principles:

  • Always include a machine-readable code (not just the HTTP status)
  • Include a human-readable message for debugging
  • Include a requestId so users can reference it in support tickets
  • For validation errors, include which field failed
// Multiple validation errors
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "requestId": "req_abc123",
    "details": [
      { "field": "email", "message": "Invalid email format" },
      { "field": "age", "message": "Must be 18 or older" }
    ]
  }
}

Versioning

APIs change over time. Versioning lets you make breaking changes without breaking existing integrations.

URL Versioning (Most Common)

GET /v1/users/42
GET /v2/users/42

Explicit, easy to understand, and works everywhere. The downside: technically violates REST (the version isn’t a resource), but this is the pragmatic choice for most teams.

Header Versioning

GET /users/42
Accept: application/vnd.myapi.v2+json

Cleaner URLs but harder to test in a browser. Use this if you have strong REST purists on the team or if your API is a long-lived platform product.

Rule: Once you publish a versioned API, never make breaking changes to it. Add fields (non-breaking), don’t remove them. Introduce new behavior in /v2, not by silently changing /v1.

Pagination

Never return unbounded lists. Always paginate collections.

Cursor-Based (Preferred)

GET /posts?cursor=abc123&limit=20

Response:
{
  "data": [...],
  "pagination": {
    "nextCursor": "def456",
    "hasMore": true
  }
}

Cursor pagination is stable — inserting new records doesn’t cause items to skip or duplicate across pages.

Offset-Based

GET /posts?page=3&per_page=20

Response:
{
  "data": [...],
  "pagination": {
    "page": 3,
    "perPage": 20,
    "total": 147,
    "totalPages": 8
  }
}

Offset pagination is simpler to implement and supports random page access. It breaks under concurrent inserts, but that’s often acceptable for non-real-time data.

Filtering, Sorting, and Searching

Use query parameters for these operations:

GET /users?status=active                    # filter
GET /posts?sort=created_at&order=desc       # sort
GET /users?q=alice                          # search
GET /orders?created_after=2026-01-01        # date range
GET /products?category=tools&min_price=10  # combine filters

Keep query parameter names consistent across all your endpoints. If it’s sort on one endpoint, it shouldn’t be order_by on another.

Security Defaults

A few non-negotiable security practices:

Always use HTTPS. Redirect HTTP to HTTPS; don’t serve APIs over plain HTTP.

Return minimal data. Don’t include internal IDs, passwords, server paths, or internal state in responses. Think about what a consumer needs, not what’s convenient to serialize.

Set CORS correctly. Don’t use Access-Control-Allow-Origin: * for APIs that handle authenticated data.

Rate limit everything. Even internal APIs. Return 429 Too Many Requests with a Retry-After header when limits are hit:

HTTP/1.1 429 Too Many Requests
Retry-After: 60
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1711000000

Documentation as Contract

The best APIs treat documentation as part of the product, not an afterthought. Use OpenAPI/Swagger to define your API schema:

paths:
  /users/{id}:
    get:
      summary: Get a user by ID
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: User found
        '404':
          description: User not found

An OpenAPI spec generates documentation, client SDKs, and mock servers. It’s the single source of truth for your API contract.

Summary

Good REST API design comes down to consistency and respecting the HTTP protocol:

  • URLs identify resources (nouns), methods express actions (verbs)
  • Use HTTP methods and status codes as intended
  • Define a standard error format and use it everywhere
  • Version from day one — breaking changes need new versions
  • Always paginate collections
  • Document with OpenAPI

The payoff is an API that developers can integrate confidently, that’s easy to maintain, and that grows without accumulating technical debt.

Level Up Your Dev Workflow

Found this useful? Explore DevPlaybook — cheat sheets, tool comparisons, and hands-on guides for modern developers.

🛒 Get the DevToolkit Starter Kit on Gumroad — 40+ browser-based dev tools, source code + deployment guide included.

Ses sistemi SON DAKİKA! Ses sistemi cezası kalktı mı?

Ses sistemi cezası kalktı mı? Trafikte güvenliği artırmayı ve çevreyi korumayı hedefleyen yeni düzenlemeler 27 Şubat 2026’da Resmî Gazete’de yayımlanarak yürürlüğe girdi. Özellikle araçlarda kullanılan standart dışı ses sistemleri ve yüksek sesle müzik dinlenmesi artık daha sıkı denetim altında olacak. Peki, araçlarda ses sistemi cezası ne kadar? Detaylar haberimizde.

OpenAI, Sora uygulamasını kapatıyor

OpenAI, metinden video üretimi yapabilen Sora uygulamasını kapatma kararı aldı. Tanıtılmasının ardından kısa sürede dikkat çeken Sora’nın hem son kullanıcıya yönelik uygulaması hem de geliştiricilere …