Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 33 of the Intermediate WordPress Plugins: REST API & React Admin course
WordPressJune 26, 20263 min read

Optimizing API Response Times: Caching for WordPress Plugins

Learn how to slash REST API response times in your WordPress plugins using object caching. Master cache invalidation and performance measurement strategies.

WordPressREST APIPerformanceCachingPHPplugin-development

Previously in this course, we covered building search and filter functionality. While your endpoints are now functional and searchable, they might feel sluggish as your database grows. In this lesson, we’ll move beyond simple query execution and introduce caching to dramatically improve your plugin's performance.

Caching for Performance: First Principles

WordPress performance is often bottlenecked by heavy database queries. When a user hits your REST API, WordPress bootstraps, authenticates, and executes SQL. If the data hasn't changed, repeating this work is wasteful.

We use the Object Cache (wp_cache_set and wp_cache_get) to store the results of expensive operations in memory. If you're using a persistent object cache backend like Redis or Memcached, this data persists across page loads, meaning your API can return a response in milliseconds rather than seconds.

Implementing Object Caching in the Service Layer

To optimize our Knowledge Base plugin, we'll cache the output of our primary GET endpoint. Instead of running a fresh WP_Query every time, we check the cache first.

Here is how you implement this pattern in your REST API callback:

PHP
function get_knowledge_base_items_cached( $request ) {
    $cache_key = 'kb_items_list_' . md5( serialize( $request->get_params() ) );
    $cached_data = wp_cache_get( $cache_key, 'knowledge_base' );

    if ( false !== $cached_data ) {
        return rest_ensure_response( $cached_data );
    }

    #6A9955">// Perform the heavy lifting
    $query = new WP_Query( [ 'post_type' => 'kb_item' ] );
    $data = array_map( 'prepare_kb_item_for_response', $query->posts );

    #6A9955">// Store in cache for 1 hour
    wp_cache_set( $cache_key, $data, 'knowledge_base', HOUR_IN_SECONDS );

    return rest_ensure_response( $data );
}

Strategic Cache Invalidation

Caching is easy; invalidation is hard. If you update a knowledge base item but the user still sees the cached version, your UI will be inconsistent. You must hook into the update process to purge the cache.

Use wp_cache_delete or wp_cache_flush to clear the relevant keys whenever data changes:

PHP
add_action( 'save_post_kb_item', 'invalidate_kb_cache' );

function invalidate_kb_cache( $post_id ) {
    #6A9955">// Clear the group so all cached lists are regenerated
    wp_cache_flush_group( 'knowledge_base' );
}

Measuring Performance Gains

Before and after optimization, you need hard data. Use the microtime(true) function to wrap your logic and log the duration to your debug log:

PHP
$start = microtime(true);
#6A9955">// ... your code ...
$end = microtime(true);
error_log( 'API Response Time: ' . ($end - $start) . ' seconds' );

For more advanced analysis, check out Optimizing Queries: WordPress Performance and Scaling Techniques to ensure your underlying SQL is lean before you even start caching. You might also want to look into WordPress performance: Preventing Cache Stampedes with Request Coalescing if your site experiences massive traffic spikes.

Hands-on Exercise

  1. Instrument your endpoint: Add microtime logging to your existing GET endpoint.
  2. Implement caching: Wrap your query logic in wp_cache_get and wp_cache_set.
  3. Verify: Open your browser's Network tab, trigger the request twice, and compare the time reported in your debug.log. You should see a significant decrease on the second request.
  4. Test invalidation: Update a post via your React admin dashboard and confirm that the next API request fetches fresh data.

Common Pitfalls

  • Cache Poisoning: Never cache data that includes user-specific sensitive information (like nonces or private user data) unless you include the User ID in your cache key.
  • Over-caching: Don't cache everything. If the data changes every second, the overhead of managing the cache might exceed the cost of the query.
  • Ignoring Non-Persistent Stores: Remember that wp_cache is non-persistent by default. If your server doesn't have Redis or Memcached configured, the cache will only last for the duration of the single request. Always ensure your environment is configured for persistence if you want real-world performance gains.

For more complex scenarios, refer to WordPress REST API Cache Invalidation: Dependency Graph Strategies to learn how to handle relationships between resources.

Recap

We've successfully moved from raw database queries to a cached architecture. By leveraging wp_cache_set and wp_cache_get with cache invalidation hooks, your plugin is now significantly faster and more scalable.

Up next: We will learn about Working with Date and Time in React to handle timestamps correctly in our admin dashboard.

Previous lessonManaging File Uploads via REST APINext lesson Working with Date and Time in React
Back to Blog

Similar Posts

WordPressJune 25, 20263 min read

Caching Strategies: Mastering Transients for WordPress Performance

Learn how to use WordPress transients to cache expensive database queries. Boost your plugin's speed and reduce database load with proper invalidation logic.

Read more
WordPressJune 25, 20263 min read

Optimizing Queries: WordPress Performance and Scaling Techniques

Learn how to optimize your WordPress queries for peak performance. Master meta_query parameters, no_found_rows, and object caching to scale your plugins effectively.

Part of the course

Intermediate WordPress Plugins: REST API & React Admin

intermediate · Lesson 33 of 45

  1. 1

    Setting up the WordPress Development Environment

    3 min
  2. 2

    Introduction to @wordpress/scripts

    3 min
  3. 3

    Configuring ESLint and Prettier

    3 min
Read more
WordPressJune 24, 20264 min read

WordPress Performance: Prefetching Middleware for Headless REST API

WordPress performance hinges on reducing cold-start latency. Learn to implement request prefetching middleware to hydrate REST API responses for headless apps.

Read more
4

Localizing Data for JavaScript

3 min
  • 5

    Anatomy of a REST API Endpoint

    3 min
  • 6

    Implementing REST API Permission Callbacks

    3 min
  • 7

    Handling GET Requests in REST API

    3 min
  • 8

    Validating and Sanitizing API Arguments

    4 min
  • 9

    Creating POST Endpoints for Data Submission

    3 min
  • 10

    Updating Existing API Resources

    3 min
  • 11

    Handling Asynchronous State in React

    3 min
  • 12

    Building the Knowledge Base Service Layer

    3 min
  • 13

    Scaffolding the React Admin Dashboard

    3 min
  • 14

    Working with @wordpress/components

    3 min
  • 15

    Creating a React Form for Submissions

    3 min
  • 16

    Implementing CRUD in the Admin UI

    3 min
  • 17

    Understanding WordPress Data Store Architecture

    4 min
  • 18

    Registering a Custom Data Store

    3 min
  • 19

    Writing Selectors for Data Access

    3 min
  • 20

    Defining Actions and Reducers

    3 min
  • 21

    Implementing Resolvers for Data Fetching

    3 min
  • 22

    Optimizing Performance with Selectors

    3 min
  • 23

    Handling Complex State Dependencies

    4 min
  • 24

    Implementing Nonce Verification

    4 min
  • 25

    Advanced Sanitization Techniques

    3 min
  • 26

    Input Validation and Error Handling

    3 min
  • 27

    Protecting Admin Screens

    3 min
  • 28

    Production Build Pipeline

    3 min
  • 29

    Debugging React in the WordPress Admin

    4 min
  • 30

    Building Search and Filter Functionality

    3 min
  • 31

    Internationalization in React

    3 min
  • 32

    Managing File Uploads via REST API

    3 min
  • 33

    Optimizing API Response Times

    3 min
  • 34

    Working with Date and Time in React

    3 min
  • 35

    Implementing Drag-and-Drop Sorting

    3 min
  • 36

    Creating Custom Hooks for API Logic

    3 min
  • 37

    Integrating with Gutenberg Blocks

    4 min
  • 38

    Handling Conflict Resolution

    4 min
  • 39

    Building a Modal Confirmation System

    Coming soon
  • 40

    Implementing Activity Logging

    Coming soon
  • 41

    Using Webpack Aliases

    Coming soon
  • 42

    Unit Testing API Endpoints

    Coming soon
  • 43

    Unit Testing React Components

    Coming soon
  • 44

    Handling Large Datasets with GraphQL

    Coming soon
  • 45

    Implementing Real-time Updates with Web

    Coming soon
  • View full course