vitessio / vitess

Vitess is a database clustering system for horizontal scaling of MySQL.
http://vitess.io
Apache License 2.0
18.56k stars 2.09k forks source link

Analyzing VReplication behavior #8056

Open shlomi-noach opened 3 years ago

shlomi-noach commented 3 years ago

I was looking into VReplication behavior as part of ongoing improvement to VReplication for Online DDL. It led me into a better understanding of the VReplication flow, and what I believe to be bottlenecks we can solve. I did some benchmarking in a no-traffic scenario (traffic scenario soon to come) to better understand the relationship between the different components. I'd like to share my findings. This will be long, so TL;DR:

Sample PR to demonstrate potential code changes: https://github.com/vitessio/vitess/pull/8044

Disclaimer: some opinions expressed here based on my personal past experience in production. I realize some may not hold true everywhere. Also, tests are failing, so obviously I haven't solved this yet.

But let's begin with a general explanation of the VReplication flow (also see Life of a Stream). I'll use an Online DDL flow, which mostly simple: copy shared columns from source to target. Much like CopyTables.

The general VReplication flow

The current flow uses perfect accuracy by tracking down GTIDs, locking tables and getting consistent read snapshots. For simplicity, we illustrate the flow for a single table operation. It goes like this:

These building blocks are essential. What's interesting is how they interact. We identify three phases: Copy, Catch-up, Fast-forward

Copy

Catchup

Side notes

Fast forward

This is actually a merger between both Copy & Catchup:

cut scene

now that we're caught up, we return to vstreamer

Benchmark & analysis of impact of factors

Let's identify some factors affecting the flow:

The below benchmarks some of these params. It is notable that I did not include a vstream_packet_size tuning in the below.

The benchmark is to run an Online DDL on a large table. In Online DDL both source and target are same vttablet, so obviously same host, and there's no cross hosts network latency. It's noteworthy that there's still network involved: the source and target communicate via gRPC even though they're the same process.

The table:

CREATE TABLE `stress_test_pk` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `sig` varchar(40) NOT NULL,
  `c` char(8) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`,`c`)
) ENGINE=InnoDB;

mysql> select * from stress_test_pk limit 10;
+----+------------------------------------------+----------+
| id | sig                                      | c        |
+----+------------------------------------------+----------+
|  1 | af15f1c7691cf684244f610e3b668e9de1dd83d6 | af15f1c7 |
|  2 | 1ccffab9bfa41d8e13fe4a8efa4764a532e6a605 | 1ccffab9 |
|  3 | a45617e5d2158c1a82fb2f98fda0106e15fe4dd2 | a45617e5 |
|  4 | fcffd065bf6e44950206617ce182b59a523986cc | fcffd065 |
|  6 | 10be967cf937218cbba69fd333020e2f1fdddd4f | 10be967c |
|  7 | 13804bb5f9e5cf8e08cc9d363790f339b761907f | 13804bb5 |
|  8 | cdb426bdddfdf660344a9bf875db911f84b30ff2 | cdb426bd |
|  9 | 7ad21b2c9261a85b558b2cdaf684ff616cad002e | 7ad21b2c |
| 13 | 94a02951925b5823fc0566a9dacbda0cad2b16cf | 94a02951 |
| 14 | d6fba9f908b703604a1b428f89d9ea6648ffe0bc | d6fba9f9 |
+----+------------------------------------------+----------+

mysql> select count(*) from stress_test_pk;
+----------+
| count(*) |
+----------+
| 16777216 |
+----------+

*************************** 1. row ***************************
           Name: stress_test_pk
         Engine: InnoDB
        Version: 10
     Row_format: Dynamic
           Rows: 15974442
 Avg_row_length: 82
    Data_length: 1325400064
Max_data_length: 0
   Index_length: 0
      Data_free: 7340032
 Auto_increment: 20578168
    Create_time: 2021-05-05 08:22:03
    Update_time: NULL
     Check_time: NULL
      Collation: utf8_general_ci
       Checksum: NULL
 Create_options: 
        Comment: 

The table takes 1.4GB on disk.

So this table is quite simple, and with some text content to make it somewhat fat.

With snapshot? Traffic? SELECT ... LIMIT copyTimeout (seconds) runtime (seconds) comments
FALSE FALSE unlimited 3600 140
TRUE FALSE unlimited 3600 140
FALSE FALSE unlimited 5 181
TRUE FALSE unlimited 5 185
FALSE FALSE 1000000 3600 166 ~10sec per round
TRUE FALSE 1000000 3600 167 ~10sec per round
FALSE FALSE 1000000 60 165
TRUE FALSE 1000000 60 165
FALSE FALSE 1000000 5 180
TRUE FALSE 1000000 5 182
FALSE FALSE 100000 3600 350 ~1.5sec per round
TRUE FALSE 100000 3600 352 ~1.5sec per round
FALSE FALSE 20000 60 infitinty like, ETA=hours
TRUE FALSE 20000 60 infitinty like, ETA=hours

For now, only consider rows With Snapshot=TRUE.

This is a subset of some more experiments I ran. The results are consistent up to 2-3 seconds across executions. What can we learn?

Now, I began by blaming this on gRPC. However, the above is not enough information to necessarily blame gRPC. Smaller timeout == more calls to vstreamer. Smaller LIMIT == more calls to vstreamer. It makes sens to first suspect the performance of a vstreamer cycle. Is it the LOCK TABLES, perhaps? Is it the transaction WITH CONSISTENT SNAPSHOT? Anything else about vstreamer? The following indicator gives us the answer:

Further development, which I'll discuss later, actually creates smaller LIMIT queries, but continuously streaming. I'll present it shortly, but the conclusion is clear: if you LIMIT without creating new gRPC calls, performance remains stable. BTW, @vmg is similarly looking into decoupling the value of vstream_packet_size from INSERTs on vcopier side; we can batch smaller chunks of INSERTs from one large vstream_packet_size.

But, but, ... What's wrong with the current flow?

It looks like a winner. BTW it is also 2 minutes faster than a gh-ost migration on same table! So is there anything to fix?

A few things:

So what I'm looking into now, is how to break down the Grand Select into multiple smaller selects, while:

  1. Not breaking the correctness of the flow, and:
  2. Not degrading performance.

(1) is easy, right? Just use LIMIT 10000. But we see how that leads to terrible run times.

Other disadvantages to the current flow:

Of course, let's not forget about the advantages of the current flow:

Anyway. If only for the sake of parallelism, I'm looking into eliminating the consistent snapshot and breaking down the Grand Select query into smaller, LIMITed queries.

The gh-ost flow

I'd like to explain how gh-ost runs migrations, without locking and without consistent snapshots or GTID tracking. gh-ost was written when we were not even using GTIDs, but to simplify the discussion and to make it more comparable to the current VReplication flow, I'll describe gh-ost's flow as if it were using GTIDs. It's just syntactic sugar.

I think we can apply the gh-ost flow to Vitess/VReplication, either fully or partially, to achieve parallelism.

The flow has two componenst: rowcopy and binlog catchup. There is no fast forward. Binlog catchup are prioritized over rowcopy. Do notice that gh-ost rowcopy operates on a single machine, so it runs something like INSERT INTO... SELECT rather than the VReplication two step of SELECT into memory & INSERT read values.

The steps:

Methodic break. We prioritize binlog events over rowcopy. This is done by making the binlog/catchup writes a REPLACE INTO (always succeeds and overwrites), and making rowcopy INSERT IGNORE (always yields in case of conflict).

consider that UPDATE we encountered in the catchup phase, and where we didn't even copy a single line. That UPDATE was converted to a REPLACE INTO, creating a new row. Later, in the future, rowcopy will reach that row and attempt to copy it. But it will use INSERT IGNORE so it will yield to the data applied by the binlog event. If no transaction ever changed that row again, then the two (the REPLACE INTO and the INSERT IGNORE for the specific row) will have had the same data anyway.

It is difficult to mathematically formalize the correctness of the algorithm, and it's something I wanted to do a while back. Maybe some day. At any case, it's the same algorithm created in oak-online-schema-change, copied by pt-online-schema-change, and continued by fb-osc and of course gh-ost. It is well tested and has been in production for a decade.

Back to the flow:

Some characteristics of the gh-ost flow:

Where/how we can merge gh-ost flow into VReplication

I'll begin by again stressing:

Otherwise, the process is sound. The PR actually incorporates gh-ost logic now:

benchmark results

This works for Online DDL; as mentioned above other tests are failing, there' still some termination condition to handle. We'll get this, but the proof of concept:

With snapshot? Traffic? SELECT ... LIMIT copyTimeout (seconds) runtime (seconds) comments
FALSE FALSE 10000 3600 140

The above shows we've managed to break the source query into multiple smaller queries, and remain at exact same performance.

It is also the final proof that our bottleneck was gRPC to begin with; not the queries, not database performance.

How can the new flow help us?

Different approaches?

At the cost of maintaining two different code paths, we could choose to:

To be continued

I'll need to fix outstanding issues with the changed flow, and then run a benchmark under load. I want to say I can predict how the new flow will be so much better - but I know reality will have to prove me wrong.

Thoughts are welcome.

cc @vitessio/ps-vitess @rohit-nayak-ps @sougou @deepthi @vmg

shlomi-noach commented 3 years ago

I realize this is a terribly long read. Not sure I'd survive it myself. If there's any thoughts before I pursue the suggested path, please let me know.

rohit-nayak-ps commented 3 years ago

Thanks for the detailed explanation/comparison of the two approaches. Since I have worked only with the current VReplication algo, I don't have an intuitive feel for which algo will perform better in the at-scale sharded Vitess deployments. Some comments/thoughts, more to clarify my understanding ...

Takeaway

The stream-first gh-ost approach is well-tested. The current copy-first approach works for all VReplication workflows. But horses-for-courses: now that we are hitting perfomance blocks we may want to implement the stream-first approach. stream-first likely provides an simpler path for movetables/reshard flows and it should be easier to concurrently copy multiple tables and parallelizing a single table copy. copy-first will still be needed for certain Materialize workflows, at least to start with.

Notes (in no particular order)

shlomi-noach commented 3 years ago

I like the terms "stream-first" and "copy-first".

Adding multiple approaches will add more code complexity.

The current state of https://github.com/vitessio/vitess/pull/8044: it's stable and working, and supports both approaches with minimal abstraction. The difference between the two isn't that big, really, in terms of code changes. Right now https://github.com/vitessio/vitess/pull/8044 supports a query comment to flag "I want stream-first" or "I want copy-first". The abstraction is therefore already complete, even if we change the mechanism (ie instead of query comment we change RPC signatures).

so the choice of algo is opaque to the enduser as far as possible.

It will be absolutely opaque to the user. According to #8044: Materialize with GROUP BY ==> copy-first. Online DDL which adds a UNIQUE constraint ==> copy-first. The rest: stream-first.

Having "insert ignore", "replace ignore" intuitively feels more expensive than a direct "insert" or "update/delete". However the current approach does have where clauses to filter out rows in catchup using PK comparisons. Maybe they cancel out.

I agree that copy-first is more efficient and does not waste double-writes. assuming we proceed with stream-first, we can also apply PK comparisons for UPDATEs, something copy-first does not support, today (for testing/mockup reasons).

Using the stream-first approach presumably the chunks can be spread out to avoid these deadlocks and index page contention.

Not sure stream-first has an advantage over copy-first in this regard.

I assume the state of a workflow in the stream-first case will be ([table, [(min PK,max PK)]], gtid)

Per #8044 the state is identical to copy-first. min-PK == lastPk anyway, and max-PK can be re-evaluated if needed (in case vreplication is restarted).

For multiple tables and a chunked single table the copy phase for the tables/chunks would be concurrent and the binlog streaming would be serialized

Right. And I wasn't even planning on running concurrent copies of chunks of same tables; I was only considering parallelizing multiple table writes.

shlomi-noach commented 3 years ago

Summary of video discussion 2021-06-01 between @deepthi , @rohit-nayak-ps and myself

We scheduled the discussion in an attempt to get a shared understanding and consensus of how we should proceed with VReplication parallelization/optimization efforts.

There are two use cases in two different trajectories:

Single table parallelization

First we concluded we must experiment a bit to see how much we can gain by parallelizing writes of a single table.

Single table optimization plausibility

I ran a hacky experiment on a ~120MB table:

I noticed a major difference if the table does or does not have a AUTO_INCREMENT column:

The latter is a bit discouraging.

Single table optimization implementation

This is entirely on the vreplication (target) side, irrespective of any changes in the streamer (source) side.

Target side receives rows up to some max-packet-size. As @vmg noted, nothing forces us to wait for the packet to fill up before writing down rows to the target table. We can choose to flush rows every 1,000 or 5,000 rows at will. Or, we can wait for, say, 50,000 rows to be fetched, and then write them down in 10 concurrent writes, each with 5,000 rows.

That part is easy. Somewhat more complicated is how we track each such write. Today we only track the last-PK written in copy_state. But with multiple concurrent writes, we may want to write down from->to of every distinct chunk, and possibly squash them once entire range (of 50,000 rows in our example) is written. Or, we can use an optimistic approach and at worst case (failure while some writes take place) re-fetch the entire 50,000 rows again and re-write them, even though some of them may have been persisted already.

We are yet to conclude whether it's worth trying to parallize writes for a single table.

Multi table parallelization

Let's consider the existing logic, which @rohit-nayak-ps coined as copy-first.

As illustrated in the original comment, this logic uses a transaction with consistent snapshot. A stream cannot read multiple tables like that and therefore we cannot parallelize tables on a single stream.

Our options are:

  1. Run multiple streams
  2. Switch to the alternate logic suggested in the original comment, which @rohit-nayak-ps coined as stream-first (or binlog-first?)

1. Multiple streams

This was the approach that was first considered when the idea for parallel vreplication first came up. Discussion points for this approach:

2. Change of logic: stream-first

https://github.com/vitessio/vitess/pull/8044 is a valid (relevant tests are passing) POC where we change the logic to avoid consistent snapshot transactions on the source tablet, which in turn allows us to read small chunks of tables at a time, which in turn allows us to potentially (not implemented yet in https://github.com/vitessio/vitess/pull/8044) read multiple tables in parallel and stream them down (mixed/sequentially).

Downside is that this doesn't exist yet, and is a change in paradigm (we will need to build trust).

Creating a POC for this is basically implementing full functionality. We need a solid and large test case.

Summary

@deepthi suggests to proceed with POC for (2) Change of logic: stream-first.

Thoughts welcome.

deepthi commented 3 years ago

Also, based on the discussion, it is likely that the consistent snapshot approach will simply not work for large VReplication-based online DDL (because we have to copy from primary->primary, and not from a replica/rdonly).

rafael commented 3 years ago

I’m not entirely up to speed with this discussion, but I wanted to chime in with some initial thoughts. Shlomi, thanks for the detailed write-up and all the careful considerations. 

In terms of the technical details of the gh-ost flow, I will have some follow-up questions. I'm still reasoning about the algorithm.

I’m asking myself a somewhat philosophical question: Are the performance benefits from this new approach worth a rewrite? 

My initial answer to this question is no. Here some points on why I’m thinking this way: 

=====

One last side note that I’ve been thinking about while digesting this proposal. I agree that the existing implementation is complex. Buuut I would argue that is conceptually is simpler. I found that it is straightforward to reason about and understand why it is correct. The opposite seems true for the gh-ost flow. Implementation is simpler, but the correctness of the approach is more complex. Granted, this could be just a side effect of my familiarity with how things work today.

=====

Also, based on the discussion, it is likely that the consistent snapshot approach will simply not work for large VReplication-based online DDL (because we have to copy from primary->primary, and not from a replica/rdonly).

I think this is a good property of existent VReplication. I would love to not lose this.

shlomi-noach commented 3 years ago

Thank you for your thoughts @rafael!

Some comments on the technical side:

my main point is that performance is not the most significant concern in this context.

That's commendable! I think some use cases require better performance: importing an entire database from an external source is one example where we've projected a multi-week operation in a real use case and with current implementation.

The following is not a technical concern: Over the years, we have accumulated knowledge across multiple people in our community about the existing implementation. We will have to go through that process again with the new implementation. For such a core functionality, this is a considerable risk for me.

The new approach is not all that different from the existing approach. If you take #8044, the change of logic is rather minor.

Will it survive a primary failover in source/destinations?

It will.

Will it survive reparents in source/destinations?

I twill.

I agree that the existing implementation is complex. Buuut I would argue that is conceptually is simpler. I found that it is straightforward to reason about and understand why it is correct. The opposite seems true for the gh-ost flow. Implementation is simpler, but the correctness of the approach is more complex.

I am yet to provide a mathematical proof of the gh-ost logic. I'm not sure how to formalize it. But it has been tested well. Anecdotally, my first logic for online schema changes, oak-online-alter-table, on which pt-online-schema-change is based, provided no test suite, and to my understanding there's yet no testing logic for pt-osc. We will build trust in the new logic by testing. We do have the luxury of already having a mechanism with a test suite, and can test the new logic by running it through the existing suite.

FWIW, coming from the gh-ost side, I personally found the current VReplication logic to be complex -- points of view?

Also, based on the discussion, it is likely that the consistent snapshot approach will simply not work for large VReplication-based online DDL (because we have to copy from primary->primary, and not from a replica/rdonly).

I think this is a good property of existent VReplication. I would love to not lose this.

Not sure how you mean? Did you mean the property of copying from replica/rdonly? This will not change. Again, the switch of logic from as presented in #8044 is basically it (though it does not introduce parallelism yet). There is no fundamental change to the flow. It's the same streamer, same vcopier, same vplayer. Streamer just reads rows in a different way and flushes them in a different way. Player runs a replace into where it used to run insert into. But there is no change to the identities of the source/target, no change in the creation of both, the communication layer of both, in the backend table tracking of the process. Really the biggest change is "no table locks, no consistent snapshot, and multiple SELECT queries as opposed to a single SELECT query".

To me the "lock/consistent snapshot/big SELECT" is intimidating. I can't imagine running a 8 hour operation that would need to maintain an open transaction with consistent snapshot on a primary. In my experience this can lead to outage. That was my main concern embarking on the task. Assuming I'm correct about the risk on a primary (and that was my clear experience at my previous job), that means you always have to rely on a replica to be handy to run some operation. I'm not sure how much of a big deal that is.

For Online DDL, the design is to run/read/write on primary. It's possible to run replica->primary, I think, but haven't explored it yet.

rafael commented 3 years ago

That's commendable! I think some use cases require better performance: importing an entire database from an external source is one example where we've projected a multi-week operation in a real use case and with current implementation.

Oh if you already have use cases where it will take multiple weeks, I definitely agree it requires better performance. I'm still curious of more details of what kind of external databases. With my current understanding of performance, it seems that is external databases that are larger than 10 TB and also resharding many tables as part of this process. Something like that??

My point around performance here is that so far, they have been solvable without major changes. There are other issues (like the one I mentioned for Materialize tables), that are blockers and we don't have solutions.

Did you mean the property of copying from replica/rdonly?

Yes, that was the property. Ah great, this is not changing.

To me the "lock/consistent snapshot/big SELECT" is intimidating. I can't imagine running a 8 hour operation that would need to maintain an open transaction with consistent snapshot on a primary. In my experience this can lead to outage. That was my main concern embarking on the task.

Original implementation here didn't use consistent snapshot and it was a short lock. So it was not opened for multiple hours. Would you have the same concern in that case? If I recall correctly, the consistent snapshot was introduced to reduce even further the duration of the locks. I wonder if that optimization actually just added a reliability risk.

The previous implementation was used at Slack extensively and we never ran into issues. For context, it was not for copy, but for VDiff. We used it when we migrated our legacy systems to Vitess. This is a similar use case to the one you describe of copying an external database. The main difference in our approach is that we didn't use the copy phase, we started from a backup and used vreplication to catch up. To your point, among others, performance was a concern for this use case and we avoided copying the data altogether.

The new approach is not all that different from the existing approach.

If this is the case, I'm less concerned. I haven't actually look at the PR yet, I was catching up with the discussion here. I still have to do my homework of reflecting more about the new algorithm.

shlomi-noach commented 3 years ago

I am not really familiar with the previous implementation, myself, so I have no insights on that. I'll ask around though.

shlomi-noach commented 3 years ago

I'm gonna pivot a bit and focus again on current implementation, coined copy-first. I mentioned earlier that one scenario binlog-first approach can't handle is adding a new UNIQUE KEY or otherwise a new unique constraint (e.g. reducing the number of columns covered by an index, introduces a logical constraint). I have recently met with multiple such situation and I'd like to accommodate them.

Moreover, I've come to realize that with copy-first approach, we can work on completely different keys on source and target. One may have PRIMARY KEY(uuid) on source and PRIMARY_KEY (autoinc_id) on target, and we can still make a schema migration consistent! The only constraint is that we still share the source key columns between the two tables, which is a significant relaxation of Online DDL limitations.

So, gonna look more closely into how we can optimize with current logic.

shlomi-noach commented 3 years ago

I have a rough draft (in my brain) of how we might run concurrent table copy using the existing VReplication logic, on top of a single stream. It will take me a while to write it down in words, and I'm still unsure how complex it would be to implement it in code.

shlomi-noach commented 3 years ago

Some design thoughts and initial work on parallel vreplication copy: https://github.com/vitessio/vitess/pull/8934