Skip to content

Read Replica just for API Requests #44

Closed

Description

@michaelrimbach

Is it possible to load the read replica settings just for WP JSON / WooCommerce API requests? My plan is that all read requests from API calls go to the read replica, everything else should go to the master db.

I thought it should work like this:

if( ! empty( DATABASE_HOST_RR ) && ( ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || ( defined( 'WC_API_REQUEST' ) && WC_API_REQUEST ) || isset( $_GET['wc-api'] ) ) ) {

$wpdb->add_database( array(
	'host'     => DATABASE_HOST_RR,
	'user'     => DB_USER,
	'password' => DB_PASSWORD,
	'name'     => DB_NAME,
	'write'    => 0,
	'read'     => 1,
	'dataset'  => 'global',
	'timeout'  => 0.2,
) );	

}

But I found out that the constant REST_REQUEST is not set when the ludicrousdb config is loaded.

Maybe the solution is to load the read replica settings via a custom plugin later (not in db-config.php file)?

Activity

  1. JJJ commented on Nov 5, 2017

    @JJJ
    Collaborator

    Hey @michaelrimbach. Good question, and one that I'm sure others will have eventually, once they've reached a scale in their store where this is a benefit to them.

    Totally not testing this myself, but I'd do something like:

    • Always define your API-only read-only database server, maybe with a specific dataset value like wcapi
    • Use $wpdb->add_callback( 'wc_api_callback' ); to make yourself a custom callback
    • Include a custom callback like the following:
    /**
     * Woo Commerce dataset override
     */
    function wc_api_callback( $query, $wpdb ) {
    	if ( ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || ( defined( 'WC_API_REQUEST' ) && WC_API_REQUEST ) || isset( $_GET['wc-api'] ) ) {
    		return 'wcapi';
    	}
    }
    

    This way, anytime those conditions are met, the correct wcapi dataset is used for any query that might be related to a WooCommerce REST API request, regardless of where it might be coming from (internal, external, whatever.)

  2. locked and limited conversation to collaborators on Jun 12, 2024
  3. converted this issue into a discussion #164 on Jun 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions