Make WordPress Core

Opened 10 years ago

Last modified 3 weeks ago

#39603 reopened enhancement

The more posts with similar names you have, the slower you save the next one

Reported by: bisyarin Owned by:
Priority: normal Milestone:
Component: Posts, Post Types Version:
Severity: normal Keywords: needs-testing has-patch has-unit-tests
Cc: Focuses: performance

Description

Hello, developers! Thank you for your work on Wordpress!

While using Flamingo for saving Contact Form 7 submissions, I encountered a huge slowdown after more than 11 000 submissions had been saved. I thought it was a Flamingo problem, but it appears that all autogenerated post-types in Wordpress can cause this problem.

Contact Form 7 saves submissions as posts with 'flamingo_inbound' type, and uses 'your-subject' slug when a form doesn't have a subject (which is my case). So, in all saved form submissions I have 'your-subject, your-subject-2, ..., your-subject-N' slugs generated by wp_unique_post_slug(). The problem is that for every new 'your-subject-N' slug wp_unique_post_slug() issues N-1 SELECT queries. In other words, wp_unique_post_slug() bruteforces a new possible slug, generating a lot of SQL queries fetching all previously saved similar posts.

You can see it if you run the attached 'generate-many-posts.php' script from your Wordpress root (more and more queries will be used for saving every new post).

Also, let me suggest a solution. With the attached patch we don't bruteforcing the slug suffix. We just get the last appropriate slug, increment it's suffix, and than use this suffix in a new unique slug.

Attachments (6)

generate-many-posts.php​ (1.9 KB ) - added by bisyarin 10 years ago.
Problem Demo
constant-time-slug-generation.diff​ (4.3 KB ) - added by bisyarin 10 years ago.
Patch enabling constant-time slug generation
constant-time-slug-generation-2.diff​ (4.7 KB ) - added by bisyarin 10 years ago.
The Second Patch of performance improving
wpUniquePostSlug-unit-tests.diff​ (5.1 KB ) - added by bisyarin 10 years ago.
filling-gaps-slug-generation.diff​ (5.2 KB ) - added by bisyarin 10 years ago.
Patch for post.php for faster slug generation with filling gaps approach
filling-gaps-wpUniquePostSlug-unit-tests.diff​ (6.8 KB ) - added by bisyarin 10 years ago.
Patch for wpUniquePostSlug.php with tests for faster slug generation with filling gaps approach

Download all attachments as: .zip

Change History (21)

@bisyarin
10 years ago

Patch enabling constant-time slug generation

#1 @johnbillion
10 years ago

  • Keywords has-patch needs-testing needs-unit-tests added
  • Type defect (bug) → enhancement
  • Version 4.7.1

Thanks for the patch, @bisyarin , and welcome to Trac :-)

This will need some testing (and unit tests) to demonstrate that the functionality continues to work as expected with edge case slugs, such as your-subject-3-2, not-your-subject-7, your-subject-suffix-2, etc.

#2 follow-up: @pento
10 years ago

Another edge case to test - when a slug on an older post has been edited. Ie:

  • Create post with slug foo
  • Create post with slug bar
  • Edit foo to have the slug bar, which should be changed to bar-2.

After that, create another post with slug bar - it should be changed to bar-3, but I think constant-time-slug-generation.diff​ will return bar-2.

#3 in reply to: ↑ 2 ; follow-up: @rmccue
10 years ago

Replying to pento:

After that, create another post with slug bar - it should be changed to bar-3, but I think constant-time-slug-generation.diff​ will return bar-2.

This could be fixed with ORDER BY post_name, right?

#4 in reply to: ↑ 3 @pento
10 years ago

Replying to rmccue:

Replying to pento:

After that, create another post with slug bar - it should be changed to bar-3, but I think constant-time-slug-generation.diff​ will return bar-2.

This could be fixed with ORDER BY post_name, right?

Nope.

mysql> DROP TABLE IF EXISTS foo;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE foo (
    -> bar VARCHAR(255)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO foo(bar) VALUES('baz'),('baz-1'),('baz-2'),('baz-10');
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM foo ORDER BY bar DESC LIMIT 1;
+-------+
| bar   |
+-------+
| baz-2 |
+-------+
1 row in set (0.00 sec)

#5 @rmccue
10 years ago

  • Keywords needs-patch added; has-patch removed

Ouch. I figured MySQL would do a natural sort here, but guess not.

The other solution I can think of would be to do ORDER BY LENGTH(post_name) DESC, post_name, but a) the performance would likely suck, and b) this would fail with foo-a-b and foo-1.

Leaving open, as we should keep exploring how to improve the performance, but switching to a direct query doesn't appear to be a good solution here.

#6 @bisyarin
10 years ago

Thank you for prompt reply, @johnbillion, @pento, and @rmccue!

You are making a good poing, @pento. I didn't even think of this situation. As a quick fix for this I would suggest 'ORDER BY post_modified DESC', but it stops working if all four events (create foo, create bar, rename foo->bar, create bar) happen on the same second. So, I'll try to find another solution.

#7 @bisyarin
10 years ago

Hello!
I've attached patches for "wp-includes/post.php" and for "tests/post/wpUniquePostSlug.php".

I decided to try @rmccue's suggestion and perform natural sort on MySQL side, selecting needed rows for sorting with RLIKE. I didn't notice serious performance issues with LENGTH or RLIKE while running the tests listed below.

Thousand Posts Creation Tests

Original trunk code:
Fresh database on each run: 329 seconds for 1000 objects (average of three runs)
With 10 000 records already in DB: ~2 hours for 1000 objects (estimation based on several minutes of work)

First patch (that works incorrectly):
Fresh database on each run: 78 seconds for 1000 objects (average of three runs)
With 10 000 records already in DB: 156 seconds for 1000 objects (one run)

Second patch:
Fresh database on each run: 79 seconds for 1000 objects (average of three runs)
With 10 000 records already in DB: 214 seconds for 1000 objects (one run)

Although the second patch works about 40% slower than the first one, it's still a nice result comparing to the original performance.

Unit tests for the issues discussed here, especially with @pento, have been created. Also I added an SQL-queries counting test.

In "phpunit\tests\post\wpUniquePostSlug.php" file, "test_embed_slug_should_be_suffixed_for_pages" test a typo has been found: paage -> page

IMPORTANT QUESTION:
The original code has a feature of filling the gaps between numeric prefixes.
For example, we have 'post', 'post-2', and 'post-4'.
In original code the next prefix is '3'. With the second patch it is '5'.

Should the behavior of filling gaps be in the code with improved performance? It's just requires PHP-side processing of all similar slug names, this is why I'm asking. Of course, this processing can be smart, but still sending all the needed slug names to PHP can slow things down. What do you think?

Last edited 10 years ago by bisyarin (previous) (diff)

#8 @bisyarin
10 years ago

  • Keywords has-patch has-unit-tests added; needs-unit-tests needs-patch removed

@bisyarin
10 years ago

Patch for post.php for faster slug generation with filling gaps approach

@bisyarin
10 years ago

Patch for wpUniquePostSlug.php with tests for faster slug generation with filling gaps approach

#9 @bisyarin
10 years ago

Hello!

If you decide to choose the original way of filling gaps in slugs numbering (it's of course slower than the second patch's way), than I've attached patches for 'src' and 'tests'. These are my tests results for this approach:

Fresh database on each run: 92.5 seconds for 1000 objects (avg of two runs)
With 10 000 records already in DB: 419 seconds for 1000 objects (average of three runs)

This ticket was mentioned in ​Slack in #core-test by hellofromtonya. ​View the logs.


5 years ago

This ticket was mentioned in ​Slack in #core-test by hellofromtonya. ​View the logs.


5 years ago

#12 @flixos90
17 months ago

  • Milestone Awaiting Review
  • Resolution → maybelater
  • Status new → closed

I think the solution to go for here is still unclear after all these years. Given the lack of inactivity for such a long time, I'm going to close this. If somebody is willing to drive this forward, feel free to reopen.

#13 @jdeep
3 weeks ago

We encountered the same issue during migration when slug collisions in content (mostly attachment slugs) caused the migration to slow down with time. We found that it ultimately boiled down to wp_unique_post_slug’s linear search for finding the first non-colliding slug. With N existing duplicates, the next post needs N queries, so importing N duplicates takes about ~N²/2 queries in total.

I have been looking into a few approaches for solving this without changing the existing behaviour of the function and I would like to get some comments on it.

Current behaviour that must be preserved

wp_unique_post_slug() returns the lowest unused suffix, starting at -2, with no upper limit. This means that it also fills gaps (if it exists) in the unbounded range.

To keep this behaviour intact, the logic must go over all the slugs one way or the other to find the first missing slug (gap).

Current Loop

Ref: ​https://github.com/WordPress/WordPress/blob/1bc6da76fc6177fa64385dde7d52754b65561020/wp-includes/post.php#L5846

suffix = 2
do {
    candidate = slug + "-" + suffix
    taken     = SELECT post_name FROM wp_posts WHERE post_name = candidate LIMIT 1
    suffix++
} while ( taken )
return candidate

It does one query per suffix.

Proposal: check suffixes in batches that double in size

suffix = 2
size   = 1

loop {
    candidates = [ slug-suffix, slug-(suffix+1), ..., slug-(suffix+size-1) ] # uses wp_truncate_slug()

    taken = SELECT post_name FROM wp_posts WHERE post_name IN ( candidates ) 

    for each candidate in candidates, in order {
        if candidate is not in taken {
            return candidate # lowest free suffix
        }
    }

    suffix = suffix + size
    size   = min( size * 2, 1000 ) # exponentially increase the batch size for slug search with limit to 1000
}

This is inspired by exponential (galloping) search (​https://en.wikipedia.org/wiki/Exponential_search): the batch size doubles each round. Unlike galloping search, it checks every suffix in each range instead of probing single points, because a gap anywhere below would make a probe misleading.

The overall behaviour of both versions of wp_unique_post_slug remains the same. The only difference is in performance. I ran some benchmarks:

  1. Table 1: Insert one new post whose slug already has N duplicates
    +------------+--------------+---------+-----------+---------+----------+
    | N existing | Current loop | Queries |  New loop | Queries | Speed-up |
    +------------+--------------+---------+-----------+---------+----------+
    |      1,000 |     84.37 ms |   1,001 |  19.23 ms |      11 |     4.4x |
    |      5,000 |    360.51 ms |   5,001 |  97.15 ms |      15 |     3.7x |
    |     10,000 |    728.11 ms |  10,001 | 195.78 ms |      20 |     3.7x |
    +------------+--------------+---------+-----------+---------+----------+
    
  1. Table 2: Inserting N posts in a row that all use the same slug
    +---------------+--------------+-----------+-----------+---------+----------+
    | N posts added | Current loop |   Queries |  New loop | Queries | Speed-up |
    +---------------+--------------+-----------+-----------+---------+----------+
    |           100 |       691 ms |     5,050 |    506 ms |     673 |     1.4x |
    |         1,000 |     37.78 s  |   500,500 |   15.72 s |   9,977 |     2.4x |
    |         2,000 |    143.95 s  | 2,001,000 |   57.70 s |  21,953 |     2.5x |
    +---------------+--------------+-----------+-----------+---------+----------+
    

This was benchmarked on my local machine and therefore, it does not account for network latency for db query. If we simulate a 0.2ms latency for each query, the numbers blow up for the current loop:

  1. Table 3: Insert one new post whose slug already has N duplicates (0.2ms latency per db query)
    +------------+--------------+---------+-----------+---------+----------+
    | N existing | Current loop | Queries |  New loop | Queries | Speed-up |
    +------------+--------------+---------+-----------+---------+----------+
    |      1,000 |    285.13 ms |   1,001 |  22.80 ms |      11 |    12.5x |
    |      5,000 |  1,440.18 ms |   5,001 | 100.82 ms |      15 |    14.3x |
    |     10,000 |  2,841.33 ms |  10,001 | 204.27 ms |      20 |    13.9x |
    +------------+--------------+---------+-----------+---------+----------+
    
  1. Table 4: Inserting N posts in a row that all use the same slug (0.2ms latency per db query)
    +---------------+--------------+-----------+-----------+---------+----------+
    | N posts added | Current loop |   Queries |  New loop | Queries | Speed-up |
    +---------------+--------------+-----------+-----------+---------+----------+
    |           100 |      1.80 s  |     5,050 |    0.67 s |     673 |     2.7x |
    |         1,000 |    142.46 s  |   500,500 |   18.75 s |   9,977 |     7.6x |
    |         2,000 |    577.58 s  | 2,001,000 |   65.67 s |  21,953 |     8.8x |
    +---------------+--------------+-----------+-----------+---------+----------+
    
Last edited 3 weeks ago by jdeep (previous) (diff)

This ticket was mentioned in ​PR #14628 on ​WordPress/wordpress-develop by ​@jdeep.


3 weeks ago
#14

wp_unique_post_slug() checked one numeric suffix per query, so a slug with N duplicates took N + 1 queries, and importing many posts with the same title grew quadratically.

The suffix search now runs in a private helper, _wp_unique_post_slug_add_suffix(), which checks candidates in exact-match post_name IN ( ... ) batches that double in size, starting at 1 and capped at 1,000. The result is unchanged: the lowest free suffix starting at 2, gaps are filled, and each candidate is truncated as before.

Additionally, The PHPStan baseline count for strlen() given an int in post.php drops from 3 to 1, since the three suffix loops are now one helper.

Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Opus 5.5
Used for: Initial research on finding element in unbounded range with gaps. Final implementation and tests were reviewed and edited by me.

#15 @jdeep
3 weeks ago

  • Resolution maybelater
  • Status closed → reopened

Here's a small script for testing the patch locally. It creates N posts with the same slug using wp_insert_post(), then times inserting one more and checks that the new post gets the expected slug.

<?php
/**
 * Times inserting a post whose slug already has N duplicates.
 *
 * Usage: npm run env:cli -- eval-file bench-39603.php [N] [slug]
 */

global $wpdb;

$n    = isset( $args[0] ) ? (int) $args[0] : 1000;
$slug = isset( $args[1] ) ? sanitize_title( $args[1] ) : 'bench-39603';

$insert = static function () use ( $slug ) {
        return wp_insert_post(
                array(
                        'post_title'  => 'bench-39603 temporary post',
                        'post_name'   => $slug,
                        'post_status' => 'publish',
                )
        );
};

$ids = array();
for ( $i = 1; $i <= $n; $i++ ) {
        $ids[] = $insert();
}

$queries = $wpdb->num_queries;
$start   = microtime( true );
$ids[]   = $insert();
$time    = ( microtime( true ) - $start ) * 1000;
$queries = $wpdb->num_queries - $queries;

$result   = get_post_field( 'post_name', end( $ids ) );
$next     = $n + 1;
$expected = wp_truncate_slug( $slug, 200 - ( strlen( (string) $next ) + 1 ) ) . "-$next";

printf( "Slug:       %s\n", $slug );
printf( "Duplicates: %d\n", $n );
printf( "Inserting post %d: %.2f ms, %d queries\n", $next, $time, $queries );
printf( "Result:     %s\n", $result );
printf( "Expected:   %s (%s)\n", $expected, $result === $expected ? 'match' : 'MISMATCH' );

foreach ( $ids as $id ) {
        wp_delete_post( $id, true );
}

Both counts include about additional queries that wp_insert_post() runs regardless of the slug. The slug search itself takes 101 queries on trunk and 8 with the patch. On trunk that number grows by one for every existing duplicate, while the patch's grows logarithmically.

Note: See TracTickets for help on using tickets.