1. Project Overview & Quickstart (vitessio/19.0.3)
Technical Documentation: vitessio/19.0.3
βΉοΈ Provenance: Multi-Tier Ingestion Β· CodeWiki Reference
19.0.3
Agent Skills & Rules
- Discovered 21 agent rule(s) and prompt configurations.
--- METRICS ---
- Files Extracted: 1
- Estimated Token Budget: ~24 tokens
- Canonical Reference: https://codewiki.google/github.com/vitessio/19.0.3
2. Official Technical Reference & Guides (vitessio/website)
File: README.md
The Vitess website
This repo houses the assets used to build the website at https://vitess.io.
Running the site locally
First install npm, then fetch dependencies, including
Hugo by running these commands:
cd website
npm installTo build a development version of the site, run the following command:
make buildTo serve the site locally, run:
make serveView the locally served site at http://localhost:1313.
Adding a user logo
If you'd like to add your logo to the Who uses Vitess section of the website, add a PNG, JPEG, or SVG of your logo to the static/img/logos/users directory in this repo and submit a pull request with your change. Name the image file something that reflects your company (e.g., if your company is called Acme, name the image acme.png).
Link checking
You can check the site's internal links by running make check-internal-links and all linksβinternal and externalβby running make check-all-links.
CSS/SASS
The Vitess website uses Bulma, a CSS (and SASS) framework that provides all kinds of variables, utilities, and components.
Adding a new learning resources filter option
To add a new filter option, simply follow these steps:
- Navigate to
resources.yamlfile to annotate:cd data/resources.yaml. - add your new filter option to all the data in the folder.
- youtube: uRB-Qni_bCM
title: "Vitess: Introduction, New Features and the Vinted User Story - Florent Poinsard, Deepthi Sigireddi, PlanetScale & Kazimieras Aliulis, Vinted"
date: 2024
type: video
FILTER_NAME = "filter_value"Replace FILTER_NAME with any desired name of your choice. Same applies to the value.
- Navigate to the
index.searchindex.jsonfile to edit:cd layouts/_default/index.searchindex.json. - Open the file and go down to line 3. You will notice the format of the data represented in a key/value pair. Just before the closing parenthesis, append your new option like this:
"FILTER_NAME" $resources.FILTER_NAME.
Replace FILTER_NAME with the same name represented in the frontmatter (see step 2 above for reference).
- Head over to
config.tomlfile. In theparams.lunrsection, you will see two arrays namedvarsandparams. Add your new filter option's name to each of the arrays:
vars = ["title", "summary", "date", "publishdate", "expirydate", "permalink", "FILTER_NAME"]- Navigate to
javascript.htmland scroll down to where the logic for resource filter is declared. Within that scope, find where thelunr()function is being called. You will notice a callback function is being passed to thelunr()function. Within the callback function, you will also noticethis.fieldbeing called with some values passed in. Append this block of code right after the lastthis.fieldfunction call:
this.field("FILTER_NAME");Replace FILTER_NAME with the same name represented in the frontmatter (see step 2 above for reference).
- Navigate to
layouts/partials/learning-resources/filter-panel.html. Locate the div with a class name offilter. Within the div, add this new block:
<div class="mt-5">
<h5>FILTER_NAME</h5>
{{ $resources := $.Site.Data.resources.resources }}
{{ $FILTER_NAMe := slice }}
{{ range $resources }}
{{ $FILTER_NAME = $years | append .FILTER_NAME }}
{{ $FILTER_NAME = uniq $FILTER_NAME }}
{{ end }}
{{ range $FILTER_NAME }}
{{ $filter := . }}
<div>
<input id="{{ . }}" type="checkbox" name="resource_filter" value="{{ . }}">
<label for="{{ . }}">{{ . }}</label>
</div>
{{ end }}
</div>Replace FILTER_NAME with the same name represented in the frontmatter (see step 2 above for reference).
- Save your changes and rebuild your frontend.
Releasing a new version of the documentation
To release a new version of the documentation you can use one of the following two scripts:
./tools/rc_release.sh: for RC release.- Takes one argument, the number of the next release.
- Usage when releasing v16.0.0-rc1:
./tools/rc_release.sh "17"
./tools/ga_release.sh: when a version becomes GA.- Takes one argument too, the number of the version we are making GA.
- Usage when releasing v16.0.0 GA:
./tools/ga_release.sh "16"
File: package.json
{
"devDependencies": {
"bulma": "^0.9.3",
"hugo-extended": "^0.96.0"
}
}
File: README-zh.md
The Vitess website
This repo houses the assets used to build the website at https://vitess.io.
Adding a user logo
If you'd like to add your logo to the Who uses Vitess section of the website, add a PNG, JPEG, or SVG of your logo to the static/img/logos/users directory in this repo and submit a pull request with your change. Name the image file something that reflects your company (e.g. if your company is called Acme name the image acme.png).
File: .htmltest.external.yml
DirectoryPath: public
IgnoreDirectoryMissingTrailingSlash: true
IgnoreAltMissing: true
File: .htmltest.yml
DirectoryPath: public/docs
IgnoreDirectoryMissingTrailingSlash: true
CheckExternal: false
IgnoreAltMissing: true
File: content/en/community.md
title: Vitess Community
Vitess is developed in the open. Here are some of the channels we use to communicate and contribute:
Slack: Vitess Slack (recommended)
Twitter: @vitessio
Stack Overflow: Vitess
Issue Tracker: Use the GitHub issue tracker for vitessio/vitess (Vitess) or vitessio/website (Documentation).
Security Vulnerabilities: Contact Vitess maintainers
Please do not ask individual project members for support. Use the channels above instead, where the whole community can help you and benefit from the solutions provided. If community support is insufficient for your situation, please refer to the Commercial Support section below.
Contributing
We welcome your contribution to Vitess, whether they be documentation, a bug fix or new feature. For more information, see the contributing guide.
Monthly Meetings
On the third Thursday of the month (unless otherwise specified), the Vitess community holds a monthly meeting by video conference to discuss the state of Vitess. New features will be previewed or discussed, and everyone regardless of location and familiarity with Vitess is welcome to join.
To stay up to date on these meetings and join them, please subscribe to the CNCF Public Events calendar.
Date: 3rd Thursday of every month
Time: 08.00 a.m. PST
If you would like to submit a topic for discussion at the meeting, please email the maintainers team, or reply to the call-for-agenda-items on the Vitess Slack a few days before the call.
Notes and agenda items from past meetings
Project Governance
Vitess is an independent open-source project and not controlled by any single company. To emphasize this we joined the Cloud Native Computing Foundation in 2018.
Within the project, we make decisions based on these rules.
Code of Conduct
To make Vitess a welcoming and harassment-free experience for everyone, we follow the CNCF Code of Conduct.
Commercial Support
This is a list of third-party companies and individuals who provide products or services related to Vitess. Vitess is an independent open source project which does not endorse any company. The list is provided in alphabetical order.
Acknowledgements
Vitess was born at YouTube in 2010, and joined the CNCF in February 2018.
File: content/en/blog/2015-03-20-scaling-mysql-in-the-cloud-with-vitess-and-kubernetes.md
author: "Anthony Yeh" published: 2015-03-20T13:53:00-07:00 slug: "2015-03-20-scaling-mysql-in-the-cloud-with-vitess-and-kubernetes" tags: [ "kubernetes", "cloud",] title: "Scaling MySQL in the cloud with Vitess and Kubernetes"
Cross-posted
onΒ Google Cloud Platform
Blog.
Your new website is growing exponentially. After a few rounds of high fives, you start scaling to meet this unexpected demand. While you can always add more front-end servers, eventually your database becomes a bottleneck, which leads you to...
- Add more replicas for better read throughput and data durability
- Introduce sharding to scale your write throughput and let your data set grow beyond a single machine
- Create separate replica pools for batch jobs and backups, to isolate them from live traffic
- Clone the whole deployment into multiple datacenters worldwide for disaster recovery and lower latency
At YouTube, we went on thatjourney as
we scaled our MySQL deployment, which today handles the metadata for billions of daily video views andΒ 300 hours of new video uploads per minute. To do this, we developed theΒ VitessΒ platform, which addresses scaling challenges while hiding the associated complexity from the application layer.
Vitess is available as an open-source projectΒ and runs best in a containerized environment. WithΒ KubernetesΒ andΒ Google Container Engine as yourΒ container cluster manager, it's now a lot easier to get started. Weβve created a single deployment configuration for Vitess that works onΒ any platform that Kubernetes supports.
In addition to being easy to deploy in a container cluster, Vitess also takes full advantage of the benefits offered by a container cluster manager, in particular:
- Horizontal scalingΒ β add capacity by launching additional nodes
rather than making one huge node - Dynamic placementΒ β let the cluster manager schedule Vitess
containers wherever it wants - Declarative specificationΒ β describe your desired end state, and
let the cluster manager create it - Self-healing componentsΒ β recover automatically from machine
failures
In this environment, Vitess provides a MySQL storage layer with improved durability, scalability, and manageability.
We're just getting started with this integration, but you can alreadyΒ run Vitess on
KubernetesΒ yourself. For more on Vitess, check out
ourΒ website, ask questions on ourΒ forum, or join us onΒ GitHub. In particular, take a look at our overview to understand the trade-offs of Vitess versus NoSQL solutions and fully-managed MySQL solutions likeΒ Google Cloud SQL.
-Posted by Anthony Yeh, Software Engineer, YouTube
File: content/en/blog/2015-10-06-cloud-native-mysql-sharding-with-vitess-and-kubernetes.md
author: "Anthony Yeh" published: 2015-10-06T13:22:00-07:00 slug: "2015-10-06-cloud-native-mysql-sharding-with-vitess-and-kubernetes" tags: [ "kubernetes", "cloud", "sharding",] title: "Cloud Native MySQL Sharding with Vitess and Kubernetes"
Cross-posted onΒ Google Cloud Platform
Blog.
Cloud native technologies like Kubernetes help you compose scalable services out of a sea of small logical units. In our last
post, we introduced Vitess(an open-source project that powers YouTube's main database) as a way of turning MySQL into a scalable Kubernetes application. Our goal was to make scaling your persistent datastore in Kubernetes as simple as scaling stateless app servers - just run a single command to launch more pods. We've made a lot of progress since then (pushing over 2,500 new commits) and we're nearing the first stable version of the new, cloud native Vitess.
Vitess 2.0
In preparation for the stable release, we've begun to publish alpha builds
of Vitess v2.0.0. Some highlights of what's new since our earlier post include:
- Using the final Kubernetes 1.0 API.
- Official Vitess client libraries in Java, Python, PHP, and Go.
- Java and Go clients use the new HTTP/2-based gRPC framework.
- Can now run on top of MySQL 5.6, in addition to MariaDB 10.0.
- New administrative dashboard built on AngularJS.
- Built-in backup/restore designed to plug into blob stores like Google Cloud Storage.
- GTID-based reparenting for reversible, routine failovers.
- Simpler schema changes.
We've also been hard at work adding lots more documentation. In particular, the rest of this post will explore one of our new walkthroughs that demonstrates transparent resharding of a live database - that is, changing the number of shards without any code changes or noticeable downtime for the application.
Vitess Sharding
Sharding is bitter medicine, as S. Alex Smith wrote. It complicates your application logic and multiplies your database administration workload. But sharding is especially important when running MySQL in a cloud environment, since a single node can only become so big. Vitess takes care of shard routing logic, so the data-access layer in your application stays simple. It also automates per-shard administrative tasks, helping a small team manage a large fleet.
The preferred sharding strategy in Vitess is what we call range-based shards>. You can think of the shards as being like the buckets of a hash table. We decide which bucket to place a record in based solely on its key, so we don't need a separate table that keeps track of which bucket each key is in.
To make it easy to change the number of buckets, we use consistent hashing. That means instead of using a hash function that maps each key to a bucket number, we use a function that maps each key to a randomly distributed (but consistent) value in a very large set - such as the set of all 8-byte sequences. Then we assign each bucket a range of these
values, which we call keyspace IDs.
Transparent Resharding
If you want to follow along with the new resharding walkthrough, you'll need to first bring up the cluster as described in the unsharded guide.
In the sample app code, you'll see a get\_keyspace\_id() function that transforms a given page number to the set of all 8-byte sequences, establishing the mapping we need for consistent hashing. In the unsharded case, these values are stored but not used. When we introduce sharding, page numbers will be evenly distributed (on average) across all the shards we create, allowing the app to scale to support arbitrary amounts of pages.
Before resharding, you'll see a single custom shard named "0" in the Vitess dashboard. This is what an unsharded keyspace looks like.
As you begin the resharding walkthrough,you'll bring up two new shards for the same keyspace. During resharding, the new shards will run alongside the old one, but they'll remain idle (Vitess will not route any app traffic to them) until you're ready to migrate. In the dashboard, you'll see all three shards, but only shard "0" is currently active.
Next, you'll run a few Vitess commands to copy the schema and data from the original shard. The key to live migration is that once the initial snapshot copy is done, Vitess will automatically begin replicating fresh updates on the original shard to the new shards. We call this filtered replication, since it distributes DMLs only to the shards to which they apply. Vitess also includes tools that compare the original and copied data sets, row-by-row, to verify data
integrity.
Once you've verified the copy, and filtered replication has caught up to real-time updates, you can run the migrate command which tells Vitess to atomically shift app traffic from the old shards to the new ones. It does this by disabling writes on the old masters, waiting for the new masters to receive the last events over filtered replication, and then enabling writes on the new masters. Since the process is automated, this typically only causes about a second of write unavailability.
Now you can tear down the old shard,
and verify that only the new ones show up in the dashboard.
Note that we never had to tell the app that we were changing from one shard to two. The resharding process was completely transparent to the app, since Vitess automatically reroutes queries on-the-fly as the migration progresses.
At YouTube, we've used Vitess to transparently reshard (both horizontally and vertically) nearly all of our MySQL databases within the last year alone, and we have still more on the horizon as we continue to grow. See the full walkthrough instructions if you want to try it out for yourself.
Scaling Benchmarks
The promise of sharding is that it allows you to scale write throughput linearly by adding more shards, since each shard is actually a separate database. The challenge in achieving that separation while still presenting a simple, unified view to the application is to avoid introducing bottlenecks. To demonstrate this scaling in the cloud, we've integrated the Vitess client with a driver for the Yahoo! Cloud Serving Benchmark(YCSB).
Below you can see preliminary results for scaling write throughput by adding more shards in Vitess running on Google Container Engine. For this benchmark, we pointed YCSB at the load balancer for our Vitess cluster and told it to send a lot of INSERT statements.
Vitess took care of routing statements to the various shards.
The max throughput (QPS) for a given number of shards is the point at which round-trip write latency became degraded, which we define as >15ms on average or >50ms for the worst 1% of queries (99th percentile).
We also ran YCSB's "read mostly" workload (95% reads, 5% writes) to show how Vitess can scale read traffic by adding replicas. The max throughput here is the point at which round-trip read latency became degraded, which we define as >5ms on average or >20ms for the worst 1% of queries.
There's still a lot of room to improve the benchmarks (for example, by tuning the performance of MySQL itself). However, these preliminary results show that the returns don't diminish as you scale. And since you're scaling horizontally, you're not limited by the size of a single machine.
Conclusion
With the new cloud native version of Vitess moving towards a stable launch, we invite you to give it a try and let us know what else you'd like to see in the final release. You can reach us either on our discussion forum, or by filing an issue on GitHub. If you'd like to be notified of any updates on Vitess, you can subscribe to our low-frequency announcement list.
-Posted By Anthony Yeh, Software Engineer, YouTube
File: content/en/blog/2016-03-03-vitess-2-0-is-now-beta.md
author: "Anthony Yeh" published: 2016-03-03T14:07:00-08:00 slug: "2016-03-03-vitess-2-0-is-now-beta" tags: [ "release",] title: "Vitess 2.0 is now beta!"
That means we've accomplished all our planned overhauls of client APIs and backward-incompatible protocol changes. See the release notes for what's new.
We're now working closely with several users who are evaluating Vitess and providing feedback on the use cases that are important for their particular applications and production environments. If you're at the same stage, we welcome you to join the discussion by posting on the mailing list.
We're also trying out Slack for more conversational topics. We don't have an automatic invite system in place, so please email [email protected] to request an invite if you're interested in joining the channel.
Lastly, we're starting our own blog (seeded with our previous guest posts on other blogs). This will be a place for our engineers to go more in-depth into various parts of Vitess.
Thanks, and happy scaling everyone!
- Anthony Yeh, Software Engineer @ YouTube
File: content/en/blog/2016-03-10-percona-live-featured-talk-with-sugu-sougoumarane-vitess-the-complete-story.md
author: "Anthony Yeh" published: 2016-03-10T11:13:00.001000-08:00 slug: "2016-03-10-percona-live-featured-talk-with-sugu-sougoumarane-vitess-the-complete-story" tags: [ "conference",] title: "Percona Live featured talk with Sugu Sougoumarane \u2013 Vitess: The Complete Story"
Cross-posted fromΒ Percona
Blog.
Welcome to the next installment of our talks withΒ Percona Live Data Performance Conference 2016Β speakers! In this series of blogs, weβll highlight some of the speakersΒ that will beΒ at this yearβs conference, as well as discuss the technologies and outlooks of the speakers themselves. Make sure to read to the end to get a special Percona Live registration bonus!
In this installment, our Percona Live featured talk with Sugu Sougoumarane,Β Infrastructure & Storage Engineer atΒ YouTubeΒ is aboutΒ Vitess: The Complete Story.Β I had a chance to speak with Sugu and learn a bit more about YouTube and
Vitess:
Percona:Β Give me a brief history of yourself: how you got into database development, where you work, what you love about it.
Sugu: My involvement with databases goes back to Informix in the 90s. This was during the 4GL and client-server days. I was part of the development team for a product called NewEra.
I later joined PayPal, where we used Oracle and eventually scaled it to the biggest machine money could buy. I have to say that Iβm still a fan of the mighty hash join. During my time there, I wrote the system that balanced the books, which helped me gain some unique perspectives on consistency. Word on the street is that the tool is still in use.
These experiences at PayPal influenced the founders of YouTube to try a different approach: scaling with commodity hardware. When I joined YouTube, the only MySQL database we had was just beginning to run out of steam, and we boldly executed the first resharding in our lives. It took an entire night of master downtime, but we survived. These experiences eventually led to the birth of Vitess.
Percona:Β Your talk is going to be on βVitess: The Complete Story.β How
hasΒ VitessΒ moved from a YouTube fix to a viable enterprise data
solution?
Sugu: This was around 2010. YouTube was growing, not only organically, but also internally. There were more engineers writing code that could potentially impair the database, and our tolerance for downtime was also decreasing. It was obvious that this combination was not sustainable. My colleague (Mike Solomon) and I agreed that we had to come up with something that would leap ahead of the curve instead of just fighting fires. When we finally built the initial feature list, it was obvious that we were addressing problems that are common to all growing organizations.
This led us to make the decision to develop this project as open source, which had a serendipitous payback: every feature that YouTube needed had to be implemented in a generic fashion. App-specific shortcuts were generally not allowed. We still develop every feature in open source first, which we would then import to make it work for YouTube.
Aside from our architectural and design philosophy, our collaboration with Kubernetes over the last two years means anyone can now run Vitess the way YouTube does: in a dynamically-scaled container cluster. Weβve had engineers dedicated to deployment and manageability on a public cloud, making the platform ready for general consumption.
Percona:Β Why move to a cloud-based storage solution anyway? What are the advantages and disadvantages?
Sugu: In general, a big advantage of cloud solutions is easy horizontal scalability β tuning capacity by simply dumping more commodity servers in the mix. For storage engines, the problem is that application complexity and operational overhead tend to scale up along with the number of database instances. A cloud-native storage solution like Vitess hides the complexity of horizontal scalability from both app developers and database operators. Thousands of servers can look like one to both dev and ops. With Kubernetes, Vitess even becomes agnostic to the underlying choice of cloud platform, providing cloud flexibility with no vendor lock-in.
Percona:Β What are the roadblocks cloud data becoming the default? What are the issues about cloud data storage that keep you up at night?
Sugu: Cloud technologies are beginning to coalesce around ideas like immutable
infrastructure and ephemeral, dynamically-scheduled workloads. Instead
of changing a server, you dynamically request a new one, and the old one
disappears. These ideas work great for stateless app servers but
represent unique challenges for storage engines. It turns out that many
of these challenges are ones we faced at YouTube as we moved Vitess from
private data centers into Googleβs global container cluster. So we know
cloud-native data storage works at scale, but now we have to prove that
it works just as well on public cloud.
Percona:Β What are you most looking forward to at Percona Live Data Performance Conference 2016?
Sugu: I feel like I still donβt know MySQL well enough. Iβm hoping to learn more
about its internals and new features. Iβm also looking forward to
learning more about todayβs data challenges that companies are facing,
and hear about the creative ways people are solving them.
Want to find out more about Sugu Sougoumarane, Vitess, and YouTube?
Subscribe to theΒ VitessΒ blog site, and check
out theΒ Vitess main page.
To hear Suguβs talk onΒ Vitess: The CompleteStory, register forΒ Percona Live Data Performance Conference
2016.
Use the code βFeaturedTalkβ and receive $100 off the current
registration price!
TheΒ Percona Live Data Performance ConferenceΒ is
the premier open source event for the data performance ecosystem. It is
the place to be for the open source community as well as businesses that
thrive in the MySQL, NoSQL, cloud, big data and Internet of Things (IoT)
marketplaces. Attendees include DBAs, sysadmins, developers, architects,
CTOs, CEOs, and vendors from around the world.
The Percona Live Data Performance Conference will be April 18-21 at the
Hyatt Regency Santa Clara & The Santa Clara Convention Center.
File: content/en/blog/2016-04-26-vitess-v2-now-with-more-v3.md
author: "Anthony Yeh" published: 2016-04-26T14:05:00-07:00 slug: "2016-04-26-vitess-v2-now-with-more-v3" tags: [ "conference", "release", "sharding",] title: "Vitess V2: Now with more V3"
Starting with Vitess v2.0.0-beta.2, the VTGate V3 API can route complex single-shard queries (containing joins, subqueries, aggregation, sorting, and any combination thereof) as well as perform cross-shard joins. That means you no longer need to tell VTGate the keyspace ID that a query targets, as you did with the VTGate V2 API.
The fact that keyspace IDs are now hidden from the application has enabled drop-in Vitess libraries for standard database interfaces likeΒ JDBCΒ (written by Flipkart), PDO (written by Pixel Federation), PEP 249, and database/sql.
We've also made it possible to do resharding without having to add a keyspace ID column to your tables, which means no more schema changes and column back-fills when migrating existing databases to Vitess.
To show off these new features, we recently gave a talk at Percona Live 2016 (no video unfortunately, butΒ the slides are posted) in which we did a live demo of resharding an app that's completely unaware of sharding. The Sharding in Kubernetes guide has been updated for the new flow, so you can try it yourself.
In the talk, we also described how VTGate V3 works under the hood, and how it evolved to encapsulate sharding - hiding more and more of the complexity of scaling from applications:
Evolution of VTGate
Vitess 1.0
- No VTGate: App determines which shard it needs, and talks directly to that shard.
Vitess 2.0
- VTGate V1: App determines which shard it needs, and asks VTGate to route to that shard.
- VTGate V2: App computes the keyspace ID.Β VTGate determines which shard that ID lives on (which can change during resharding) and routes there.
- VTGate V3: App sends queries as if the DB is unsharded. VTGate computes the keyspace ID, determines which shard(s) the requested data live on, and routes there.
One of the most common questions we get is, "When will Vitess 3.0 be out so we can use the V3 API?" Hopefully the summary above makes the answer more clear: V3 is here now. In fact, VTGate V1 and V2 are not going away; they're just different modes of talking to VTGate, and each still has valid use cases.
The confusion was caused by our unfortunate naming choices for these features, and was made worse as we started abbreviating "VTGate V3" to just "V3" over time. In our defense, naming things is known to be one of the few truly hard problems in computer science. Going forward, we hope to fix this by giving more descriptive names to the different VTGate modes, and revamping the documentation to reflect those new names. In the meantime, please let us know on our mailing list if you have any
other questions or suggestions.
File: content/en/blog/2016-06-07-distributed-transactions-in-vitess.md
author: "Sugu Sougoumarane" published: 2016-06-07T17:05:00-07:00 slug: "2016-06-07-distributed-transactions-in-vitess" tags: [ "distributed transactions", "sharding", "2PC",] title: "Distributed Transactions in Vitess"
With Vitess introducing sharding and allowing you to create cross-shard indexes, distributed transactions become unavoidable for certain workloads. Currently, Vitess only supports best-effort distributed transactions. So, itβs possible that a distributed commit only completes partially, leaving data in an inconsistent state.
At this point, 2 Phase Commit (2PC) is the only known protocol that allows you to give atomic guarantees for distributed transactions. For this protocol to work, a database must be able to support the βPrepareβ contract. However, not all databases provide such support. Also, some of the engines that do support it either do it incorrectly or inefficiently. Specifically, the pre-5.7 MySQL XA protocol works incorrectly for replication, and is therefore not usable.
The question was asked: Is it possible to build a Prepare protocol on top of a database that does not support it? The answer is: Yes, for an engine like MySQL. The explanation follows.
2PC in very few words
If nothing ever failed, 2PC would not be needed. You just open transactions with databases as needed, and commit them all at the end. However, there are failure modes in the system that cause one of these things to happen:
- A database aborts a transaction for internal reasons.
- A database refuses to commit because of lock conflicts.
- A database crashes and loses an uncommitted transaction.
2PC introduced the prepare protocol to defend against the above three. A database that acknowledges a prepare must give you the following guarantees:
- It will not abort a transaction unless requested.
- It will never refuse a commit.
- If the database crashes, it will reinstate the transaction to its prepared state upon recovery.
With the above guarantees, a transaction manager asks all participants to prepare. If any of them fails, then the decision is to rollback. If they all succeed, then we have the guarantee that commits will never be refused. So, we can decide to commit. Once a commit (or rollback) decision is made, itβs final. If a database crashes after a prepare, the recovery process will reinstate the prepared transaction. At this point, the transaction manager can resolve the transaction according to the final decision.
2PC itself has failure modes. The most significant issues are related to the transaction manager crashing, or the ability for various parts of the system to agree on the commit/rollback decision. These issues are somewhat orthogonal to the focus of this document, and they will be covered in the upcoming design doc, or possibly in a different blog post.
MySQL transactions
MySQL transactions have an interesting property: If all statements have executed successfully, then a commit almost never fails. There are a few configurations where this is not true. So, they should be avoided:
- Group replication: This is a new 5.7 feature. If this is turned on, then a commit can fail due to locking conflicts.
- Semi-sync with a commit timeout: If configured this way, MySQL could fail your commit if it doesnβt receive a semi-sync packet within the timeout. To make 2PC reliable, itβs recommended that semi-sync be configured with no time-out. This way, if acks are not received on time, the entire database would lock up and will be treated as crashed. In the case of Vitess, the system will initiate a failover to a healthier replica. Of course, the new master will not have the original transaction, but weβll rely on a different mechanism for reinstatement, which is explained in the next section.
Because a commit could never fail, MySQL will never rollback your transaction unless itβs requested.
The above behavior basically tells us that MySQL transactions are in a pseudo-prepared state all the time. They satisfy properties 1 & 2 of the prepared state, but not #3.
Redo logs in the database
Now, all we have to do is figure out a way to get back to the prepared state when a database crashes. In order to achieve this, the traffic will have to be sent through a proxy.
- The proxy will maintain a list of statements that are sent in a transaction. When a βprepareβ is requested, the list will be saved to a redo_log table. This will be done in a separate transaction while the original transaction is still open. If this operation fails, then the prepare is treated as failed.
- Letβs say that a database crashes after some transactions are prepared, and weβre performing a recovery. After the database part of the recover, the proxy scans the redo log for prepared transactions, and replays each of those in independent connections. These should not fail because of the serializability of transactions. Once this is done, we have fulfilled the 3rd requirement of the βPrepareβ contract. After this step, the proxy can start accepting normal traffic. At this time, the transaction managers can re-connect to the proxy to conclude the prepared transactions.
Coincidentally, Vitess already has such a proxy in VTTablet. How convenient.
In Vitess, the usual way to βrecoverβ a failed master is to failover to a replica by designating it as the new master. A tool like Orchestrator will do this reliably almost all the time. Various levels of semi-sync settings further improve these guarantees. In other words, the same effect of reinstating prepared transactions can also be achieved if we used the failover workflow instead of a traditional recover.
Recap
Vitess allows you to tune MySQL to suit your durability requirements. If youβre very paranoid about data loss, you can tune-up the semi-sync variable to have almost the same reliability level as Paxos. Using MySQL 5.7βs version of βlosslessβ semi-sync will further strengthen this. However, these could be overkill. Typically, requiring a single semi-sync ack for any version of MySQL is likely sufficient. In the rare case of a transaction loss, the 2PC mechanism should be able to detect and alert you, and manual intervention can be used to perform repairs. These failure modes will be covered in the detailed design doc.
Coupling this with fast failure detection and automatic master failover also gives you high availability.
This basically means that a node is unlikely to lose your committed data, and will also be resurrected very quickly if it crashes or experiences a network partition.
The proposed prepare mechanism effectively extends the durability and availability guarantee of a single database (or shard), and makes it work equally reliably for distributed transactions that span multiple shards.
Loose ends
The purpose of this blog post is to show that itβs possible for Vitess to
support atomic distributed transactions. There are still many details to
cover:
- Generating globally unique transaction ids to avoid number conflicts.
- Isolation levels.
- Reliably storing commit/abort decisions.
- Transaction manager failures.
- Database and network failure scenarios.
- Optimizations.
These issues will be addressed in a detailed design doc under vitess.io very soon.
File: content/en/blog/2017-04-25-vitess-releases-version-2-1.md
author: "Sugu Sougoumarane" published: 2017-04-25T15:59:00.002000-07:00 slug: "2017-04-25-vitess-releases-version-2-1" tags: [] title: "Vitess releases version 2.1"
The Vitess project is proud to announce the release of version 2.1. This version comes packed with new features that improve usability, availability and resilience of the overall system.
The release coincides with the Percona Live 2017 Conference, where project co-founder Sugu Sougoumarane will give the talk "Vitess beyond YouTube".
He is joined by Robert Navarro from Stitch Labs Β who is going to describe how Stitch Labs uses Vitess in production.
Version 2.0 introduced a sharding agnostic API to the world. This allowed clients to connect to Vitess and send queries as if it was a single database engine. However, questions remained about the atomicity of transactions that spanned multiple shards or keyspaces. With 2.1, you
can now request such transactions go through the Two-Phase Commit (2PC)
protocol that gives you all-or-none cross-database commits.
Another noteworthy new feature is the support for the native MySQL protocol. This allows users to trivially repoint their application to a Vitess instance without any code modifications. Over the next few months, this protocol will be solidified and made a first class citizen of the Vitess API.
We would like to thank our community for their contributions. Several companies have adopted Vitess, provided extensive feedback and submitted major code changes. For example, Hubspot extended the SQL parser and BetterCloud added TLS support in the JDBC driver.
The full list of new features in 2.1 and upgrade instructions can be found in the release notes.
About Vitess
Vitess strives to be be the best performing, scalable and most available NewSQL storage solution in the Cloud based on MySQL. It has been battle-hardened by serving YouTubeβs video metadata traffic for over six years now. Since its inception it was developed as an open-source project, and has a growing community of users and contributors.
About Percona Live
The Percona Live Open Source Database Conference 2017 is the premier event for the diverse and active open source database community, as well as businesses that develop and use open source database software. The conferences have a technical focus with an emphasis on the core topics of MySQL, MongoDB, PostgreSQL and other open source databases. Tackling subjects such as analytics, architecture and design, security,
operations, scalability and performance, Percona Live provides in-depth
discussions for your high-availability, IoT, cloud, big data and other
changing business needs.
File: content/en/blog/2017-09-18-custom-sharding-with-vitess.md
author: "Sugu Sougoumarane" published: 2017-09-18T07:15:00-07:00 slug: "2017-09-18-custom-sharding-with-vitess" tags: [] title: "Custom Sharding With Vitess"
Vitess supports a variety of predefined sharding algorithms that can suit different needs. This is achieved by associating a Vindex with your main sharding column. A Vindex essentially provides a mapping function that converts your column value to a keyspace_id. This keyspace_id is then used to decide the target shard.
A full description of VSchema and Vindexes can be found
here. However, such predefined vindexes will work only if you intend to shard your system using Vitess. What if you're already sharded? Would it be
possible to make Vitess accommodate your sharding scheme? This blog
intends to cover such a use case.
Vitess is indeed capable of accommodating any sharding scheme because of its pluggable Vindex API. In fact, all the predefined vindexes of Vitess are plug-ins themselves. In order for Vitess to accommodate your sharding scheme, all you have to do is define a Vindex that performs such a mapping.
Use Case
The following example is inspired from my conversations with Simon
Mudd of Booking.com, who had a database that was already sharded 4-way using a mod-based scheme. Given an input column, say user_id, Booking.comβs sharding function yields values from 0-3, which decides the target shard for each request.
To make a Vindex work for the above use case, you have to do two
things:
- Assign keyranges to each of your shards
- Define a Vindex that maps the input to a
keyspace_idsuch that it falls in the corresponding keyrange.
In Vitess, a keyspace id can be any binary string. For simplicity, letβs restrict our keyspace ids to be the big-endian representation of a 64-bit number. If so, they will have a fixed length of 8 bytes. If we were to uniformly split such keyspace ids into four shards, they would be as follows:
| keyrange (last value excluded) | abbreviated |
|---|---|
| 0x0000000000000000-0x4000000000000000 | -40 |
| 0x4000000000000000-0x8000000000000000 | 40-80 |
| 0x8000000000000000-0xC000000000000000 | 80-C0 |
| 0xC000000000000000-(highest number) | C0- |
Now, all we have to do is provide a function that generates a keyspace id
such that it remaps the mod function into this wider space. In the above
case, it could be achieved with the following expression: (user_id%4)<<62.The keyranges assigned to the original shards will be as follows:
| shard | keyranges |
|---|---|
| 0 | -40 |
| 1 | 40-80 |
| 2 | 80-C0 |
| 3 | c0- |
Once you have provided this Vindex, the application can go back and forth between legacy code and Vitess because they should both route queries the same way. After gaining confidence in the new system, you can fully migrate to using Vitess.
How to reshard
Because of the expanded set of possible keyspace ids, many strategies can be adopted. The end goal is to produce more distinct numbers than the original scheme in such a way that they continue to map to the same shards.
Let's see what it takes to go from 4 to 8 shards. These can be represented as: -20-40-60-80-A0-C0-E0-.
With this shard layout, a simple user_id%8<<61 will not work. This is because the numbers produced by this function will not fall in the same shard range as the ones produced by the mod 4 function. Here is an illustration:
user_id%4<<62
| input | 0000...0101 |
|---|---|
| %4 | 0000...0001 |
| << 62 | 0100...0000 |
| Hex | 0x40... |
| Mapped Keyrange | 40-80 |
user_id%8<<61
| input | 0000...0101 |
|---|---|
| %8 | 0000...0101 |
| << 61 | 1010...0000 |
| Hex | 0xA0... |
| Mapped Keyrange | 80-C0 (different shard) |
For things to work correctly, the new mapping function must yield values that land in the same keyrange as before, which is not the case in the above example.
One could devise a complicated bit-manipulation algorithm that generates new values in a way that is backward compatible with the old function. One such function would be: (user_id%4)<<62 + ((user_id>>2)%2)<<61). While the original function generated two material bits, the new function will generate three material bits. But the original two material bits will be as before. For example, if the original function produced 10β¦,
the new function would produce 100β¦ or 101β¦. This means that you can replace the original function with the new one, and this function would work for four as well as eight shards.
Verifying the correctness of the above formula is left as an exercise to the reader.
The problem with this approach is that the formula gets progressively more complex every time you reshard.
The ReverseBits Strategy
There is a simpler approach: if we looked more closely at how the od function worked, it essentially truncates the more significant bits of the input number. What if, instead of shifting the bits, we reversed them The new function would instead be: ReverseBits(user_id%4). With this function, the original shard mappings will be different (1 & 2 will be swapped):
| shard | original | new |
|---|---|---|
| 0 | -40 | -40 |
| 1 | 40-80 | 80-C0 |
| 2 | 80-C0 | 40-80 |
| 3 | C0- | C0- |
The advantage of this approach is that it later allows us to change the vindex to ReverseBits(user_id%8). This would produce numbers that are backward compatible with the mod 4 scheme, but will produce twice the number of distinct output values. Here is a repetition of the above example using the new functions:
ReverseBits(user_id%4)
| input | 0000...0101 |
|---|---|
| %4 | 0000...0101 |
| ReverseBits | 1000...0000 |
| Hex | 0x80... |
| Mapped Keyrange | 80-C0 |
ReverseBits(user_id%8)
| input | 0000...0101 |
|---|---|
| %8 | 0000...0101 |
| << 62 | 1010...0000 |
| Hex | 0xA0... |
| Mapped Keyrange | **80-C0 (pre-shard)**A0-C0 (post-shard) |
The next obvious question is: why mod at all? What if we just used ReverseBits(user_id)? It turns out that this would also work. There was really no need to perform the mod in the first place. Once youβve transitioned to using ReverseBits, you can shard at will from any number to any number. Over time, you can forget that you ever used mod-based sharding.
This is now available as a predefined Vindex as reverse_bits.
Can you think of other ways to perform such migrations? Join us on our Slack channel to share your ideas. You can send an email to [email protected]
to request an invite.
Happy Sharding!
File: content/en/blog/2018-08-05-vitess-weekly-digest.md
author: "Adrianna Tan" published: 2018-08-05T07:15:00-07:00 slug: "2018-08-05-vitess-weekly-digest" tags: ['Weekly Digest'] title: "Vitess Weekly Digest - Aug 5 2018"
This week, we kick off our new weekly blog updates β bringing you the best of Vitess questions and topics on our Slack discussions. The goal is to show the most interesting topics and requests so those of you just getting started can see highlights of what has been covered.
Since this is our first ever digest, weβre going to go back in time and publish a little more than what happened last week.
Large result sets
Alejandro [Jul 2nd at 9:54 AM]
Good morning, we are trying to move away from interacting with Vitess through gRPC and instead using the MySQL binary protocol and I was just wondering if anyone here could let me know if Vitess supports unbuffered/streaming queries (returning more than 10K rows) over the MySQL binary protocol, or if that is just a gRPC feature? Thanks in advance. (edited)
sougou [29 days ago]
@ Alejandro set workload='olap' should do it (for mysql protocol)
Naming shards
Deepak [9:36 AM]
Hello everyone, I have a small doubt can someone please help me with it? I have four shards in Vitess cluster but all the data are going in just one shard. One of the difference in the setup is shard nomenclature. Instead of giving -80, 80- etc as shard names (params to -init_shard flag to vttablet) I have given names 0, 1, 2, 3. Can this be the cause of all data going to just one shard?
sougou [10:11 AM]
@ Deepak yeah. shards have to be named by their keyrange
DB config parameters simplified
sougou [10:06 AM]
yay. no more long list of db command line options for vttablet: https://github.com/vitessio/vitess/pull/4088
all db-config-XXX options are now deprecated.
acharis [10:08 AM]
but will still work?
sougou [10:08 AM]
yes
acharis [10:08 AM]
great
sougou [10:08 AM]
till 3.0, then I'll delete them
MySQL 8.0 support
hrishy [7:33 PM]
does vitess support mysql 5.8 and the native json in particular
sougou [7:41 PM]
@ hrishy I assume you mean 8.0. Although it hasn't been tried, we think it should work.
derekperkins [7:49 PM]
the new 8.0 JSON functions wonβt work yet, those have to get added to the parser, but if thatβs a blocker for you, itβs pretty easy to add
derekperkins [8 days ago]
https://github.com/vitessio/vitess/issues/4099
Replica chicken-and-egg
faut [1:01 AM]
Hello. I need some help migrating to vitess. I have a baremetal master running mysql 5.6 and vttablet pointing to that master. I can query the master through vttablet and vtgate. The replicas however are still empty and cannot replicate because they donβt have the correct schema. I thought I could try make it a rdonly tablet and do the copy but that says no storage method implemented (assuming because it is not managed by mysqlctld) Iβm not sure what the best approach from here is.
sougou [6:21 AM]
@ faut you can setup the replicas independent of vitess: manually copy the schema and point them at the master, just like you would to a regular mysql replica
mysqlctl is good only if you want vitess to manage the mysqls from the ground up.
but if you want to spin up a brand new replica, you first need to take a backup through vtctl
then spinning up a vttablet against an empty mysql will restore from that backup and automatically point it to the master
faut [6:24 AM]
yea, Iβm stuck at the point of making the backup through vtctl. I want to try get away from managed the sql servers.
If I had a replica/rdonly with the schema manually copied would it manage to copy all the data from the existing master?
I am able to do a GetSchema off the master but cannot just restore that schema to the rdonly/replica.
sougou [6:26 AM]
there is a chicken-and-egg problem here
because you can't take a backup from a master
faut [6:26 AM]
Yes :joy:
sougou [6:26 AM]
so, you need to manually bring up one rdonly replica
and take a backup using that
after that you can spin up more
(we need to fix that limitation). there's an issue for it
Vitess auto-fixes replication
sjmudd [5:52 AM]
Hi all. I was a bit surprised by something I saw today in Vitess. I had a master which was configured on βthe wrong portβ, so to simplify things I adjusted the configuration and restarted vttablet and mysqld. Clearly changing the port the master was listening on broke replication so I went to fix the replica configurations by doing a stop slave and was going to do a change master to master_port = xxx only to find it had given me an error: replication was already running. It looks like vttablet will βfixβ the master host:port configuration if replication is stopped and restart replication.
Wasnβt bad but was unexpected.
sjmudd [5:52 AM]
Is this expected? (Iβd guess so). What other magic type behaviour does vitess do and when? @sougou?
sougou [6 days ago]
vttablet will try to fix replication by default. You can disable it with the -disable_active_reparents flag. If you're managing mysql externally to vitess, this should be specified for vttablet as well as vtctld.
skyler [6:08 AM]
Is there a document anywhere that lists the kinds of SQL queries that are incompatible with Vitess?
derekperkins [6:24 AM]
@skyler it depends whether your queries are single shard or not
single shard supports most any query since it is just passed through to the underlying MySQL instance
cross-shard is much more limited
sjmudd [7.12 AM]
also there are several things even a single shard wonβt handle well: e.g. setting/querying session/global variables
use of query hints.
many of these things may not be a concern.
but if you use them can require code changes.
Sougou: while it is configurable I think you should probably show the default vitess version as 5.7.X as 5.5.X is rather antique right now.
Iβve changed my setup to advertise as 5.7.X. Is there a need to show such a low version? iirc this can lead replication to behave differently as the i/o thread sometimes takes the remote version into account. Iβd guess most other things may not care.
sougou [8:09 AM]
yeah. we can change the default now. most people are on 5.7 now
acharis [9:17 AM]
i think vtexplain might be what you're looking for
skyler [6 days ago]
nice! Thank you. I was unaware of that.
derekperkins [6 days ago]
Thanks, I couldn't remember for sure what the current iteration was called
File: content/en/blog/2018-08-24-vitess-weekly-digest.md
author: "Adrianna Tan" published: 2018-08-05T07:15:00-07:00 slug: "2018-08-24-vitess-weekly-digest" tags: ['Weekly Digest'] title: "Vitess Weekly Digest - Aug 24 2018"
This week, we continue the digest from the Slack discussions.
Update stream
Jian [Jul 25th at 1:27 PM]
hi there, I'm new to Vitess, now I'm following the user-guide from vitess.io to explore vitess, in update stream section, I notice they have change log, where could I see these change logs so I can have a better understanding of the update stream?
sougou
That's the only documentation we have about the update stream, but we'll be fixing docs for all vitess very soon.
Jian
sure sure, thank you very much!
vamsi
@sougou even if documentation is not ready yet, is there some info you can provide to Jian about where he can see change logs?
sougou
The end to end test can actually be handy. Let me get the link.
sougou
https://github.com/vitessio/vitess/blob/master/test/update_stream.py
sougou
this section in particular https://github.com/vitessio/vitess/blob/master/test/update_stream.py#L222
Jian [1 day ago]
:+1:
Fixing a failed MigrateServedTypes
Vidhi [2:10 AM]
Hi
for slave rollback, this will work? ./lvtctl.sh MigrateServedTypes -reverse test_keyspace/0 rdonly
sougou [6:36 AM]
yes. that should work
Vidhi [6:48 AM]
If in case some error came during master switch, as for rollback (no reads and writes are happening), if I update the old master end-point in zookeeper . Will it work?
sougou [6:50 AM]
i think you have to manually repair. can you show me where it failed?
Vidhi [6:50 AM]
It didnt failed yet. I havent done the switch. Just want to figure out rollback plan if something went wrong
Can you please elaborate on manually repair. How to do that?
sougou [6:51 AM]
let me look it up
for master switch, what vtctld does is the following:
set a shard control record to disable query service on source master, and issue a refresh which also sets the source master read-only (edited)
then waits for replication to catch up.
Once caught up, it sets the shard control record to enable query service on destination masters, and issue a refresh on destination masters that makes them read-write.
If there is a failure in the middle, you have to manually do or undo the setting of the tablet control
using SetShardTabletControl command
and then issue a RefreshStateByShard to the relevant tablets
i'm working on improving this part: https://github.com/vitessio/vitess/pull/4034
sougou
#4034 vreplication: change to use new vt.vreplication
This change deprecates vt.blp_checkpoint in favor of vreplication, which stands for Vitess Replication.
The goal is to make vreplication a standalone sub-module of vitess that other services can use, including the resharding worflow.
The big change in the model is that vreplication is not owned by the resharding workflow. The workflow instead creates vreplication streams as needed, and controls them individually. The stream id for a replication is now generated by vreplication, which the resharding workflow stores and tracks.
This also means that a vreplication stream can be directly created and managed by anyone as needed. This allows for newer and more flexible workflows in the future._
Vidhi [7:00 AM]
Can you share the complete command to do these steps. I coulnt find it vitess docs
sougou [7:01 AM]
vtctl -h gives me this: SetShardTabletControl [--cells=c1,c2,...] [--blacklisted_tables=t1,t2,...] [--remove] [--disable_query_service]
to enable query service, you probably should use --remove
to disable --disable_query_service
I haven't used these myself. So, you should test them out yourself to make sure they work as intended.
You can try it out on the source master while it's serving queries to see if it stops serving
and re-enable it with --remove
Vidhi [7:04 AM]
Sure, will try this setup on stage first.
Thank you very much for the help :)
Reading from replicas
skyler [Jul 31]
Does vtgate support rewrite rules similar to ProxySQL? Weβre using ProxySQL to send queries to a replica if itβs not too laggy.
Does vtgate, or some other component of the stack, support something similar?
I havenβt found much in docs and via google, so I assume no, but I thought Iβd ask anyway.
sougou
@skyler can you give an example?
skyler
The actual config is pretty lengthy, but what weβre doing is matching for the string /*SLAVE OK*/ at the beginning of every query. If that string exists, then we route a query to a read replica if itβs replication lag is less than some threshold. If a replicaβs replication lag is greater than the threshold, ProxySQL βshunsβ it, which means that it removes the replica from the list of replicas that are available for querying.
sougou
this is supported differently by vitess
sougou
you can specify db name as db@replica
sougou
and the tolerances you mention can be specified to vttablet
skyler
Oh interesting, thatβs very cool.
Reconstructing zk data
vamsi [Jul 31st]
Do people who use vitess with ZK generally backup ZK data regularly? If not, what would happen if ZK data is somehow corrupt or if ZK dies for some unexpected reason?
sougou
zk data can be reconstructed if needed.
it's mostly metadata about keyspaces and shards
but it's still a good idea to back it up
vamsi
any tools that can reconstruct it?
sougou
to manually reconstruct? they would be the vtctl commands like CreateKeyspace etc.
You could probably write a shell script to do this
Will be interesting if we could do a feature that generates this.
ameet
@vamsi we are using consul. We backup the vitess metadata every 30 mins. It has saved us at least once where an operator deleted the metadata by mistake. Also, we manually backup before doing the cutover operation for a shard split
sougou
If you loose all data. I think these steps will also work:
Recreate all the cells
Restart all vttablets
Perform
TabletExternallyReparentedon all master tablets
Your system should be pretty much restored to the old state.
Are primary keys needed
faut [Aug 1st]
Is it imperative for tables to have a primary key in vitess?
derekperkins
itβs pretty much imperative in MySQL to have a PK, but I donβt think Vitess adds any more need for it. Are you wanting to run sharded or non-sharded?
faut
non-sharded. We have some tables that donβt have PKs, and vitess throws cannot identify primary key of statement on updates and inserts.
sougou
it will work if you change mysql to RBR
Can sequence tables be in a sharded keyspace
captaineyesight [Aug 1st]
Hi. Iβm looking at sequences and Iβm a little confused. Lets say I have a sharded cluster: foo 00-80 and foo 80-FF. In foo, I have a table named bar that has a lovely vschema that splits it between shards. Where does the bar_seq table go? 00-80 or 80-FF or should it be in a completely different place?
weitzman
The sequence table does not need to be in the same keyspace. The vitess examples tend to use a keyspace called βlookupβ or something like that
The sequence table only has one row, so if you put it in the same keyspace it would end up in whatever tablet the primary key β0β maps to
If someone really didnβt want to go through the trouble of having multiple keyspaces there might be an argument to do that, but under normal circumstances youβd probably want the sequences in an unsharded keyspace
captaineyesight
thanks
sougou (update)
Submitted https://github.com/vitessio/vitess/pull/4134: vschema: allow pins in vschema. This allows you to pin a table to a specific shard by assigning a keyspace id to it.
Creating replicas for devs
faut [Aug 2nd]
What are the suggestion for devs in minikube and simulating the effects of vitess (Assuming they will just run mysql with a DB named the same as the keyspace? So if they write toxic queries they know before they get to a staging environment etc.
And is it possible to dump a keyspace(sharded/unsharded) so you can replicate that in a standalone mysql? ie: Is it possible to migrate out of vitess? (edited)
sougou
@faut I don't fully understand the question. Are you talking about migrating into vitess, or out?
To migrate out, you can just start sending queries directly to the mysql instances and tear down the vitess components. You could also replicate the data out and failover.
faut
:+1: Makes sense. But weβd need to rebuild/revert all the sharding?
sougou
Or reimplement sharding at the app layer
If mysql can handle, you can also merge back all the shards into one
faut
And do you have suggestions for how to βreplicateβ the database for devs. Or what to do for a dev environment? running vitess locally seems overkill.
sougou
If it's just to make the data available to devs, you can always setup a standalone replica from a vitess master.
faut
How can I restore that standalone from the backups created from vitess backup?
sougou
yeah. you can restore from those backups and point the restored db to the master if you're lazy, you could make vitess do it for you
bring up a replica vttablet. once it's brought up, kill just the vttablet
(and delete its tablet record)
faut
is manually restoring the data just a case of copying the GCS bucket to datadir?
sougou
i believe so (don't know the mechanism for GCS)
vitess copies the data files into the datastore as files
so, if bucket==file, it should work the same way in reverse
faut
cool. Then theoretically I should be able to make a backup by just copying the files there. Then restoring from that on vttablet.
sougou
should work
faut
Thank you, Iβve got a couple of ideas I will try.
Hackathon!
raj.veerappan [Aug 2nd]
Another question on https://vitess.io/docs/overview/scalingwithvitess/#migrating-production-data-to-vitess
In that approach, you'd enable MySQL replication from your source database to the Vitess master database.
In the replication approach, does "Vitess master database" mean use the VTGate as the replication slave? Or the VTTablet of the master or the mysql of the master? If it's mysql of the master, does that populate the schema properly in Vitess?
faut
hey raj, if youβre planning to do a production migration to vitess maybe we can chat. Weβre also planning to move to vitess so weβre struggling through similar issues.
raj.veerappan
I'm just doing this for a hackathon to prove things out and see if it'll work for us
sougou
People have adopted more approaches than those mentioned in that write-up. We need to update it with the new strategies
sougou
Dual-writes seems to be a popular approach
In that particular descrption, I think it meant mysql->mysql
raj.veerappan
what happens to the schema in that case?
I guess I thought updates to the schema have to go through vtgate
sougou
not necessary
even after you're fully migrated to vitess, you can deploy schema changes directly to the mysqls
and people often do, using tools like gh-ost, etc
the ApplySchema is just a convenience
raj.veerappan
hmm, ok, I made that assumption because one approach I tried was to copy over the data files from my non-vitess mysql to the data directories of the vitess mysql instances. Then when I fired up vtgate and used the mysql command line client to inspect the db, I could see all the tables were there
but when I tried to select rows from a table, vtgate complained that it didn't recognize the table
sougou
ohh. you still need a vschema
something that describes how your shards are layed out
https://vitess.io/user-guide/vschema/
sougou [18 days ago]
if the target db is not sharded yet, the vschema is a simple json that lists the table names
raj.veerappan
nice! thank you, will try that now
sougou
https://github.com/vitessio/vitess/blob/master/examples/demo/schema/lookup/vschema.json
examples/demo/schema/lookup/vschema.json
{
"sharded": false,
"tables": {
"user_seq": {
"type": "sequence"
},
"music_seq": {
"type": "sequence"
},
"name_keyspace_idx": {}
}
}tables should have no types. the sequence tables are special case
raj.veerappan
right was gonna say, I didn't think I needed to create those until I sharded things
sougou
vitess will work without a vschema as long as there's only one keyspace, because it knows there's only one
as soon as you have more than one, it needs to know where to route the queries
raj.veerappan
when you say work without a vschema, will it function purely as a "connection pool" or will it still need to parse the queries and will only support the statements it supports?
sougou
it will still do some work, but most queries will just be passed through
raj.veerappan
one of the reasons I tried copying over the data files directly was that when I tried restoring from a mysqldump vtgate complained that it couldn't handle one of the insert statements to a many-to-many mapping table because it didn't understand the primary key
sougou
it's probably because the mysqls are setup as SBR
we recommend RBR now. Hopefully we can deprecate SBR support soon :slightly_smiling_face:
raj.veerappan
oh interesting, I didn't realize that would affect mysqldump
faut
would the vschema tables just be: tables: { user: {} }?
sougou
"user":... yeah
raj.veerappan
will retry importing using mysql dump after switching all the vitess instances to RBR, seems easier than creating that json
faut
raj, are you working in GCP or baremetal?
sougou
if it's a single keyspace, you shouldn't need that json (irrespective of how you do the import)
raj.veerappan
@sougou I think I may just be in a weird state right now because the mysql import failed halfway, will start over after wiping things out and see if I can just copy the data files over without doing anything with vschema
raj.veerappan
@faut I'm just doing baremetal for the hackathon, if we start using it in production it would be with k8s/AWS (edited)
faut I had the same problems when I mounted the datadir for a single database. It showed all the tables if i did show tables it showed everything. But any query would say. the table didnt exist. Even direct to mysql
sougou
it may be related to vttablet not having reloaded the schema
vttablet reloads the schema every X minutes
faut
I did a vschema reload. But the problem is with mysql. Because even when querying directly it would fail
sougou
this is vttablet seeing the table. vschema is for vtgate (edited)
raj.veerappan
vttablet reloads the schema every X minutes
is there a way to force this?
sougou
yeah. vtctl ReloadSchema
faut
raj, if you come right with the datapath mounting please let me know. I couldnβt get it to work
sougou
there is a way to make vttablet auto-detect by making it watch the replication stream. most people prefer not to use that feature
i think the flag is -enable_replication_watcher (not at my comp)
raj.veerappan
I wiped everything out and restarted and copied the data files over, when I login through vtgate I see the tables but in the UI for vitess the schema says empty and I'm not able to select from any of the tables in mysql client connected to vtgate
did vtctl ReloadSchema against my master vttablet but the schema did not populate in web UI
so will try using the json and enumerate the table names
actually, will switch all the vitess mysql instances to RBR and try loading from mysqldump first
nice, that seems to be the way to go, only problem now is that our mysqldump has tables with foreign key constraints on tables that are defined further down in the dump and vtgate doesn't like that, will need to edit the dump and reorder the create table statements
sougou
whatever works :slightly_smiling_face:
Raj.veerappan
problem is that it seems like vtgate does not support disabling foreign key checks for loading from dump
raj.veerappan
even trying to disable for session throws
`mysql> set foreign_key_checks=0;
ERROR 1105 (HY000): vtgate: http://localhost:15001/: unsupported construct: set foreign_key_checks=0`
(edited)
raj.veerappan
well, I found a janky workaround that makes this easy, create a schema only mysqldump, open up mysql cli onto vtgate, run source repeatedly until the table count stabilizes. Then source your data only dump, super janky but it works for my hackathon :slightly_smiling_face:
I made it work the proper way, didn't realize I just needed to load the mysqldump directly against the vitess mysql master instance and reloadschema and everything would "just work"
sougou
yeah. that would be the best.
faut
The problem for me with the mysqldump is the downtime. Snapshotting a disk and using it as a mount is much quicker. I have got things to work with the mysqldump. Just trying to figure out the best way to migrate in production.
Configuring the app to use VTGate
Sean Gillespie [Aug 2nd]
Is there documentation on setting up an app to use vtgate? I canβt find much beyond saying the apps can use it like MySQL
sougou
there's not much to it. just point the app at vtgate on the mysql port
https://vitess.slack.com/archives/C0PQY0PTK/p1527271545000268
Command to connect to vtgate: mysql -h 127.0.0.1 -P 15306 -u mysql_user --password=mysql_password
Posted in #vitess May 25th
if you have many vtgates, you can put them behind an ELB
Sean Gillespie
Where do you set the user/pass?
sougou
in a credentials file like this https://github.com/vitessio/vitess/blob/master/examples/local/mysql_auth_server_static_creds.json
{
"mysql_user": [
{
"MysqlNativePassword": "*9E128DA0C64A6FCCCDCFBDD0FC0A2C967C6DB36F",
"Password": "mysql_password",
"UserData": "mysql_user"
}
],
"mysql_user2": [
{
"Password": "mysql_password",
"UserData": "mysql_user"
}
],
"mysql_user3": [
{
"MysqlNativePassword": "*9E128DA0C64A6FCCCDCFBDD0FC0A2C967C6DB36F",
"UserData": "mysql_user"
}
],
"vt_appdebug": [
{
"Password": "vtappdebug_password",
"UserData": "vt_appdebug"
},
{
"SourceHost": "localhost",
"Password": "",
"UserData": "vt_appdebug"
}
]
}and give that to vtgate (look at vtgaet-up,sh) in that same directory
Overriding the db name
raj.veerappan [Aug 2nd]
unfortunately looks like flyway relies on information_schema for a bunch of logic and that's not available through vtgate
sougou
if you connect to a specific shard, vtgate will pass it through
it should be an unsharded keyspace, or something like ks:-80
raj.veerappan
but then the db name will be vt_db instead of just db
I'll just disable flyway for now since migrations will probably need to be reworked if we use vitess
sougou
you have another option
you can override the dbname
vttablet command line -init_db_name_override (edited)
and name the db as db instead of vt_db
raj.veerappan [18 days ago]
lol, that might simplify things
Overriding the db name
raj.veerappan [Aug 2nd]
Seems like the ./lvtctl.sh CopySchemaShard test_keyspace/0 target/0 doesn't work if test_keyspace has tables with foreign keys in it
sougou
yeah. You can do a custom schema deploy in that case
it's only a convenience
raj.veerappan
is there a gist for that too :slightly_smiling_face:
I guess I only need to deploy the schema for the particular tables that I'm vertically sharding?
will just do a show create table on it on test_keyspace and just run directly using mysql on target
sougou
yup
raj.veerappan
if vtworker cannot find MASTER tablet for destination shard for target/0 even though I did the InitShardMaster step, is there something else I need to do?
I see the target keyspace in the web ui with its shards and one tagged as master correctly
sougou
check the status page for vttablet /debug/status and the logs. Maybe it didn't initialize correctly
raj.veerappan
status is healthy
sougou
and it shows up as master in vtctld?
raj.veerappan
yes
sougou
the vtworker would have written a logfile
can you see if it has more info there?
can you also show me your vtworker command?
raj.veerappan
./sharded-vtworker.sh VerticalSplitClone --tables my_table target/0
will check the log file
the only error besides the cannot find MASTER... one is proc.go:85] unexpected error on port 0: Get http://localhost:0/debug/pid: dial tcp [::1]:0: connect: can't assign requested address, trying to start anyway
sougou
what is the full error? (that error can come from three different places)
raj.veerappan
ohh, just noticed that it was in a cell that doesn't match mine
ahh, I updated the cell name in the other scripts but not in sharded-vtworker.sh
sougou
that will do it :slightly_smiling_face:
raj.veerappan
that was it :slightly_smiling_face:
been at it all day, starting to miss things
sougou [18 days ago]
don't forget about MigrateServedFrom (not MigrateServedTypes)
File: content/en/blog/2018-09-10-vitess-weekly-digest.md
author: "Sugu Sougoumarane" published: 2018-09-10T07:15:00-07:00 slug: "2018-09-10-vitess-weekly-digest" tags: ['Weekly Digest'] title: "Vitess Weekly Digest - Sep 10 2018"
This week, we continue the digest from the Slack discussions for Aug 3 2018 to Aug 31 2018.
Secondary Vindexes
raj.veerappan [Aug 3 9:27 AM]
how do secondary vindexes work? would they result in further sharding?
weitzman [9:32 AM]
If you have an authors table and a books table and you shard by author ID, a secondary vindex is a performance tool to help respond to the query, select * from books where book_id = :id
Being sharded by authors, thereβs not any obvious information in that query to help identify what the associated author ID / keyspace ID would be for the book entry (edited)
A secondary vindex is a function that helps answer that question in a more effective way than just doing a scatter query across all shards
raj.veerappan [9:35 AM]
ahh got it
so sharding only happens by primary vindex and secondary vindexes help with routing to primary vindexes.
Update streams like Maxell
raj.veerappan [10:56 AM]
I think I heard that Vitess lets you listen to a stream of db updates, similar to Maxwell, are there docs available on this?
found https://vitess.io/user-guide/update-stream/
- Note update stream has been replaced by VStream
sougou [10:57 AM]
yup :slightly_smiling_face:
it needs to be beefed up a bit. It could be easily upgraded to send full row values for RBR
https://github.com/vitessio/vitess/blob/master/test/update_stream.py is a test that also shows how to use it.
Migrating from existin MySQL
sumitj [Aug 13th at 3:25 AM]
hi , How easy it is to migrate from existing mysql stack to vitess ? it would be really helpful if we can document migration strategy and challenges in that .I think there are lot of mid size companies who use mysql and facing scaling issues in some way , it would be great if we can make this transition smooth . (edited)
faut
I think it depends on how much downtime and risk you can take.
Doing a mysqldump and restoring to a new vitess cluster seems relatively easy but it requires a lot of downtime.
faut
And also if your DB is sharded etc increases the migration complexity
sumitj
@faut, I know there will be certain challenges , but if the steps would be nicely documented then it would be easier to adopt best practice and less chance for any unexpected issues .
sougou
This is on my list of things todo
sumitj
thanks a lot @sougou
sjmudd
another thought: it depends heavily on what you have running already and how you have it set up. In theory putting vitess on top of an existing replication setup shouldnβt be hard but in practice youβll probably have to modify existing infrastructure to be at least partially vitess aware. I tried going along that route and found it troublesome. Itβs possibly easier to migrate tables to a new clean system which you can test and use without affecting existing production. That then requires you to think about how you want to move data over or if youβre comfortable putting vitess on top or whatever, but managing Vitess is different to managing a normal MySQL replication setup however you have that running at the moment.
Ordering by text strings
xuhaihua [Aug 22nd at 3:06 AM]
Case sensitive should be consistent in gate and MySQL.
sougou
Is this for table names?
xuhaihua
not table names, for row values
xuhaihua
for example there two shards and a table t, select a from t order by a asc; MySQL returned result is case insensitive.
shard1 return values: [o P]
shard2 return values: [o r ]
vtgate merge the two result in a heap:
merge shard1 o, current result : [o]
next we should merge shard2 o, but the compare in vtgate is case sensitive, the next pop is P
merge shard1 P ,current result : [o, P]
...
the final result is [o P o r]
the correct result should be [o o P r]
if the gourp by , shard1 o and shard2 o will not merged, it will be two group. (edited)
sougou
In your case, vtgate should have given an error saying that it cannot compare text columns.
what is the column type in your case?
However, if you specify a column's type in vschema, like this: https://github.com/vitessio/vitess/blob/master/data/test/vtgate/schema_test.json#L78
then it will produce a plan like this: https://github.com/vitessio/vitess/blob/master/data/test/vtgate/aggr_cases.txt#L81
which will yield the correct results.
xuhaihua
wow, understand, I didnβt know weight_string before ,awesome:+1:
Packing multiple instances in a VM
Srinath [Aug 22nd at 9:07 PM]
Can we configure one vttablet to be a master of one shard and to be a replica of another shard?
Srinath
If yes, would like to know if this is a recommended pattern, if not, would like to know the reasoning behind
sougou
i remember someone asking this question, but don't remember the answer anymore. What's the use case?
Srinath
we have an application that is distributed across many VMs. for other applications that are part of these VMs, data is stored in cassandra. the application that we write uses postgres, but none of the existing solutions help us automatically re-shard and abstract the sharding logic. hence we have chosen to keep postgres stateless and only one node is a leader, when leader goes down, all state is lost. but this poses limitations to scale of our application.
we are evaluating vitess to see if we can have a database solution that gives easy re-sharding abilities, with some guarantees w.r.t consistency & performance. we also like the fact that vitess abstracts out the sharding routing logic so that our application need not know about the topology of the database clusters at all.
that said, we are trying to see if we can come up with an architecture using vitess that will help us add more data storage capacity as more nodes are added to the cluster. initially we start from one VM, then scale out to 3, 5 etc as the need arises.
one possible architecture for 3 nodes is that have one shard and make all three nodes part of the same shard and have one master. but when we scale-out to 5 nodes, it gets complicated as to we have 2 shards, that can have 2 masters 3 replicas, but when we get to this architecture, there will be an imbalance in the replica count for shards as one shard will have two replicas and the other one will have only one replica.
another possible way to look at this is to not have database/vitess running on all nodes. basically for 5 node cluster, use only 3 node database configuration and for probably more than 5 node cluster, come up with a 6 node vitess configuration which will have 2 master shards and 4 slaves with 2 slaves per shard.
other way to look at this is to form a ring (like cassandra) where one have many shards that can be mapped on to available servers and make every available server a leader for some of the shards and follower for other shards. very much the way cockroach db is also architected. but that would mean that one vttablet instance should become both a master and a replica at the same time.
would like to know your thoughts.
sougou
i think you're assuming that you can run only one mysql per node.
vitess allows you to pack multiple mysqls per host.
so, there's no need to overload a replica onto a master
if you have host1, host2 and host3 (and say, 3 shards)
Srinath
yes, we have come up with the same configuration where one node has more than one mysql, vttablet instance running, with one of it is master and other one is replica for some other master. is that the recommended configuration?
sougou
yes. that's the recommended config
Srinath
alright, lets see how our benchmarking goes :slightly_smiling_face:
sougou
if you run like this, you just have to make sure that a replica is never on the same host as the master.
because that can cause loss of durability
Srinath
yes, we are aware of it
Srinath
thank you for your thoughts :slightly_smiling_face: (edited)
Avoiding stray tablet records
Mark Solters [Aug 27th at 10:45 AM]
I have noticed that when vttablets go down, vtctld has no idea? e.g. I follow the example tutorial, and make a single unsharded test cell (1 master, 2 read replica, 2 read only) and these show up fine when I ListAllTablets. But, when those pods go down (for example, if I kill them/they OOM/get evicted for any reason) ListAllTablets continues to list those now non-existant replicas as having an IP. Restarting vtctld does not resolve this. Am I missing something necessary to keep the state of the tablets synced with the vitess control plane here?
sougou
Yeah. This is a limitation of how things work. VTTablet is responsible for registering and unregistering the record. But it can't unregister if it's killed.
This also causes other issues: if you reparent later, the vtctld ends up waiting for a long time to change the master on the dead vttablets
We could have an agent that performs a sweep and remove orphaned records, but it's dangerous
Mark Solters
hmm, so what is the recommended approach to keep the pods alive/synced?
sougou
the recommended approach is to have another vttablet restarted with the same id if the pod dies
Mark Solters
for example, in the beginning tutorial, the pods are created directly. should they die for any reason (they OOM frequently using the specs out-of-the-box) they do not come back
so I was thinking Iβd try to spin up vttablets as statefulsets to preserve those unique ids/disk relationships
the same pod id?
sougou
the same tablet id
Do we need multiple vtctlds?
Mark Solters [Aug 28]
a bit of confusion here with vtctld: is there one instance per cell? it seems thereβs only one per cluster
but it does accept an argument like -cell {{cell}}, but this is only global in the tutorial. is this a shortcut for ease of explanation? does each cell in fact need its own vtctld? why wouldnβt there be a vtctld with -cell=test?
sougou
a single vtctld per cluster is likely sufficient. Some people launch 3, just in case.
the cell parameter in vtctld is just an old legacy thing. We need to remove that requirement.
Designing ahead for sharding
ruant [Aug 29th at 12:51 AM]
So totally dumb question...
What should i think about when designing a DB that i want to shard in the future (since this startup is of course taking of like a rocket soon :sweat_smile: )
sougou
The easiest approach is to think that you need to shard this right now, and if so, how would you do it.
ruant
I guess splitting it up by each tenant, since it's multi tenant db.
Not all tables have a tenant id on it, but if you follow the relationship all rows in the db eventually will hit a table that has a tenant id...
How advanced can I define these sharding keys? (vindex if i'm not mistaken?)
sougou
Yeah. You can shard things such that all rows related to a tenant live together.
ruant
Nice :slightly_smiling_face:
But i'm still able to query across all the data even if it's sharded.
I guess it will go faster? Since it's being processed by two "db's"
I should just take a few hours to read up on this sharding topic.
Sorry for all the questions.
sougou
There are a few approaches with different trade-offs. The TL;DR: for secondary tables: if you don't have a tenant id, you may need to incur the overhead of going through a slower vindex (backed by lookup tables)
ruant
Thanks for your replies @sougou
Really appreciate it :slightly_smiling_face:
Vitess sequences are globally unique
skyler [Aug 31st at 9:25 AM]
Do Vitess sequences support auto_increment_increment and auto_increment_offset?
sougou
The offset can be set by initializing a starting value in the sequence table (I think it's next_id). But there's currently no support for something like auto_increment_increment). Reason: typically, people set this value when they do custom sharding and want different masters to generate non-overlapping ids. But this is not required for vitess sequences because they generate globally unique ids.
skyler
Custom sharding, right, thatβs exactly why we use it. If possible I wanted to keep IDs unique across different Vitess installations, using the same scheme.
but Vitess sequences are globally unique, aha, I did not know that
Thank you!
Feature like Debezium (CQRS)
Lucas Piske [Aug 31st at 11:58 AM]
I'm developing a project where I'm using vitess as the sharding engine for mysql and I would like to use Debezium to implement CQRS. Do you think its possible to integrate this two technologies? Do you forsee any challenges that could cause problems?
koz
There will most likely be problems
It looks like Debezium uses the binlog to produce the changelog
Since Vitess is distributed you would need to connect to the binlog of each shard
It looks like Debezium supports that, but it would require additional configuration
@sougou Just implemented a feature called vreplication which might support the same feature set you are looking at with debezium
sougou
It's a POC, but we'll make into a real product soon
Lucas Piske
That would be great
I think it would be a really cool feature
It would help to implement some eventual consistency patterns
Thanks for the help
sougou
I'll definitely announce when the feature is ready
File: content/en/blog/2018-09-24-vitess-weekly-digest.md
author: "Sugu Sougoumarane" published: 2018-09-24T07:15:00-07:00 slug: "2018-09-24-vitess-weekly-digest" tags: ['Weekly Digest'] title: "Vitess Weekly Digest - Sep 24 2018"
This week, we continue the digest from the Slack discussions for Sep 1 2018 to Sep 21 2018. As of this post, we are fully caught up on our backlog.
Tracking progress of resharding
jk [Sep 5th]
In the SplitClone Stage of resharding, how can i get the percent of process ? Or Could I estimate the time left ?
sougou
I don't know of a formal way, but you can look at the database size. It should be a good indicator hopefully.
jk
Alright. I'll check the mysql data size and compare. It is almost 400G in the source shard. So I'm not sure how long it will take. Thank you.
xuhaihua
@jk just check the row size of the destination shard and the source shard in vtctld.
Proposal to reduce vitess CPU usage
sougou [Sep 9th]
Whoever is concerned about CPU: https://github.com/vitessio/vitess/issues/4191
SHOW FULL FIELDS FROM
captaineyesight [Sep 9th at 6:15 PM]
Is there anyway to get around 1105 vtgate: http://<vtgate-addr>/: syntax error at position 17 near 'FIELDS': SHOW FULL FIELDS FROM? We are using rails, and I believe this is required.
koz
Do you have the full query?
It looks like the grammar support SHOW FULL COLUMNS FROM.
I may have a simple PR that will add in FIELDS for you.
captaineyesight
Excellent. I think it is show full fields for table name.
koz
@captaineyesight try this https://github.com/vitessio/vitess/pull/4192
(PR has now been merged)
Locking primitives
sjmudd [Sep 10th at 1:40 AM]
Does vitess expose any locking primitives to do administrative tasks? I want to do a backup on one of my replicas globally but have more than one cell. I can clearly use things outside of vitess (e.g. talk to zookeeper/etcd directly) but given vitess is talking to the topology service it would be nice to use vitess to do this and thus be agnostic to whatever vitess is using.
sougou
vitess has built an api for such a thing which it uses internally. For example, to prevent multiple vtctlds from racing on the same action. But it's all go code.
sjmudd
That would be fine. Perhaps you can point me at that or a sample way of getting some global lock that would be useful.
sougou
i found this: https://github.com/vitessio/vitess/blob/master/go/vt/topo/locks.go
you can obtain keyspace or shard level locks
but i thought there was a different locking scheme. i'll need to dig further
I'll post here if i find something better.
Found it: https://github.com/vitessio/vitess/blob/master/go/vt/topo/conn.go#L165
// NewMasterParticipation creates a MasterParticipation
sjmudd
Thanks. I will take a look. In many ways this simplifies the doing stuff and means that the process is agnostic to the topo service being used.
Vitess with no special drivers
Mark Solters [Sep 10th]
I have what I hope is a very trivial question about vtgate: is it possible to perform a simple SQL operation such as e.g. a data import, but have that come in through vtgate so its automatically routed appropriately? Without using some kind of application-level driver?
In the tutorial and documentation material everything Iβve seen along these lines already has a specific master tablet in mind.
For example, if I have some .sql file that has data from many databases, and I have a schema such that those databases are separated into their own keyspaces, is there a single endpoint I can hit with vitess so that the SQL from each database goes to the appropriate keyspace, instead of having to manually connect to each shardβs master?
sougou
@Mark Solters you just summarized the whole purpose of vitess :slightly_smiling_face:
Mark Solters
I know, but my difficulty is this particular implementation: using the vtgate, but without using e.g. some python or golang driver.
sougou
vtgates support mysql protocol.
Mark Solters
yes, is there more documentation than this? https://vitess.io/user-guide/mysql-server-protocol/.
sougou
Basically, any program that speaks mysql, you should be able to point it at vtgate. there are some caveats: some things that work with single mysql don't work in a sharded system.
Like setting global parameters, or information_schema queries etc.
Mark Solters
So just to clarify, there is no documentation of the actual implementation of the mysql protocol? Or maybe it is so simple that i am simply looking for more than there is.
sougou
Yup. Just point your mysql app at it. We do need to document what works and what doesn't. That's coming soon.
Mark Solters
When vtgate looks at the /mysqlcreds/creds.json file, does the vtgate binary actually create those users in the tablets? or does authentication βterminateβ at the vtgate binary, and all tablet operations are performed with e.g. vt_dba? (edited)
sougou
The latter, but they're performed as vt_app. You can use the table acl feature to do access control at the vitess level.
Cancel resharding
** weitzman [Sep 10th at 4:02 PM]**
I havenβt synced in the vreplication stuff yet, but Iβve noticed that pre-vreplication things get weird if you forget to clean up blp_checkpoint and re-run SplitClone. You may end up with having to manually populate blp_checkpoint and create the source shard entries
sougou
in the future, there may be other workflows that may create vreplication streams
the more correct thing will be to cleanly delete vreplication through a CancelResharding command, which I intend to implement.
How to write a parser in Go
sougou [Sep 11th]
Gophercon video is out: https://youtu.be/NG0s3-s3whY.
Resharding in Kubernetes
Sean Gillespie [Sep 12th at 9:06 AM]
Using vitess in kubernetes what is the best way to add shards to a keyspace? Iβm using vitess-operator and it seems like the obvious solution is update the yaml with sharding info and let it create new pods, but I kinda assume there are some extra steps to migrate data and create new masters and such
derekperkins
youβll have to run through the resharding workflow
Iβm not sure how much the operator supports you on that https://vitess.io/user-guide/horizontal-sharding-workflow/
koz
I think you can add new shards to the operator, but you need to add all the new shards, then run through the workflow and fail over traffic, then you can remove the old shards
So for while you are doing split clone you need to have the old shards and new shards online
Sean Gillespie
Ah so that may be tricky with operator then huh? Would I just give an additional definition for that keyspace that includes shards and then do the migration from the old ones to the new ones?
koz
If you do a kubectl apply that should just spin out the extra nodes
you would just need the cluster record to contain both.
( the old shards and the new shards )
Emergency reparent
longfei [Sep 14th at 9:17 PM]
How to change replica to master when the original master is down? Is there any document?
sougou
EmeregencyReparentTablet (typo)
longfei
is EmergencyReparentShard ?
:+1: i'll take a look at it. thanks
sougou
or that one
Resource estimation
** Mark Solters [Sep 17th at 7:11 AM]**
in the documentation (production planning) it notes that you can think of giving vttablet as much CPU as your mysqls may have been using previously. this gets me in the ballpark but what Iβm left wondering is what is the recommendation as far as CPU assigned to the mysql container itself?
e.g. if i have a vttablet that has 2-4 CPUs, is the rule of thumb to give the mysql sidecar that same amount of CPU? are there any guidelines here?
Or are the estimates being provided (2-4CPUs) actually the total for both the vttablet and mysql containers taken together, and if so, what should the relative CPU ratio between them be?
sougou
MySQL's CPU is harder to estimate because it's workload dependent. Best way is to start with some assumptions and iterate.
Range should be in the order of 2-10K QPS per core.
Even for vttablet, we've seen 50-100% in CPU variance. So, take those recommendations with a pinch of salt :slightly_smiling_face:
derekperkins
@Mark Solters the recommendations in the helm chart are sourced from a few companies in production and are per container, not combined.
HubSpot use of Vitess
skyler [Sep 17th]
Our first big project has been migrating all 400+ of our MySQL databases from standalone instances into Kubernetes with the help of the Vitess project.
I know some folks from HubSpot are in this channel. Are you able to give any more details on this? Are you really running all of your MySQL in Vitess? Thatβs pretty impressive.
acharis
We're on our way there. It's a pretty cool project.
hmcgonigal
Very big portion of our production env is on vitess, yes.
acharis
And all of our QA (that we care to mention).
skyler
Sure
hmcgonigal
With the goal of having 100% of prod vitess very soon.
skyler
Thatβs awesome. Thatβs a big sign of confidence.
hmcgonigal
:+1:
derekperkins
@skyler HubSpot is also unique in how they use Vitess, based on their original microservice setup. They had hundreds of small dbs, as mentioned in the article, vs having a few big dbs that needed sharding.
skyler
Right, true. Thatβs a fortunate starting position to have.
derekperkins
It helps to show how flexible Vitess is.
File: content/en/blog/2018-11-12-vitess-weekly-digest.md
author: "Sugu Sougoumarane" published: 2018-11-12T07:15:00-07:00 slug: "2018-11-12-vitess-weekly-digest" tags: ['Weekly Digest'] title: "Vitess Weekly Digest - Nov 12 2018"
We continue the digest from the Slack discussions for Sep 22 2018 to Oct 5 2018. We've fallen slightly behind on this, but will catch up again soon.
Enable VtGateExecute in vtctld
Arsalan [Sep 22nd]
Hi,
I want to query vitess on vtgate but I have below error. How can i fix this problem?
vitess@vtctldv3-hrl74:/$ vtctlclient -server 10.5.61.20:16999 VtGateExecute -server 10.5.61.21:16991 "show tables"
E0923 05:14:55.169771 1102 main.go:61] Remote error: rpc error: code = Unknown desc = query commands are disabled (set the -enable_queries flag to enable)
sougou
you need to add this flag to vtctld:
-enable_queries
if set, allows vtgate and vttablet queries. May have security implications, as the queries will be run from this process.
Multi-column Primary Key
sjmudd [Sep 26th]
Question: if a mysql table has a multi-column primary key, can Vitess handle this ? I vaguely remember the answer might be βnoβ.
but looking in vschema_test.go I think that may not be the case.
sougou
multi-column pk should work. What we don't fully support yet are multi-column vindexes.
there's partial support for multi-column lookup vindexes, where we write multiple columns, but only use the first column for computing the keyspace id.
Vitess wins InfoWorld Bossie award
sougou [Sep 26th]
"The best open source software for data storage and analytics": https://www.infoworld.com/article/3306454/big-data/the-best-open-source-software-for-data-storage-and-analytics.html#slide9
Also, @acharis and @tpetr have been accepted to present vitess at kubecon: https://kccna18.sched.com/event/Gras/vitess-at-hubspot-how-we-moved-hundreds-of-mysql-databases-into-kubernetes-tom-petr-alexander-charis-hubspot
Splitting sharded and unsharded tables
Mark Solters [Sep 27th]
If one were to shard foo/0 to baz/{-80,80-}, would the SplitClone foo/0 syntax have to be modified to reflect that the destination shards are no longer in the source keyspace?
Inspecting the command seems to suggest that there is no βdestination shardsβ option for SplitClone. In this case, my question is better phrased as βHow can we horizontally reshard one keyspace into another?β It seems the missing part is convincing foo/0 that it βoverlapsβ with baz/-80,80-.
I think the correct answer here is that I should be vertically sharding.
sougou
Yeah. you first have to vertical shard from foo/0 to baz/0, and then reshard baz to baz/{...}
Mark Solters
I see. Is there a guide or set of instructions for the vertical sharding procedure?
sougou
It's one of the top items that we need to document. In the meantime, you can look at my scripts. Steps are similar to horizontal sharding: https://gist.github.com/sougou/e6259e958b5707d5888a5ac406418cc3
Mark Solters
Very interesting! Iβve basically done these steps minus thisCreateKeyspace --served_from 'master:test_keyspace,replica:test_keyspace,rdonly:test_keyspace' target
Is that step strictly necessary? If I have already copied over the relevant CopySchemaShard, and baz already has a functional master etc. can I simply run VerticalCloneSplit?
i ask because i notice VerticalCloneSplit specifies the destination but not the source.
(The thread was forgotten at this point)
Answer: The specific step is strictly necessary for SplitClone. It's currently a rigid workflow that we plan to make more flexible in the future.
Show tables of a keyspace
mgersh [Sep 27th]
is there a query to show all tables for a certain keyspace? we are using the jdbc driver
"show tables from $keyspace" just returns the default keyspace's tables
leoxlin
If you connect to a specific Keyspace, you can use SHOW TABLES;
If pods crash, check resource limits
mshivanna [Oct 1st]
hi we recently spun up vitess cluster now we want to import a mysql dump. what is the right way to do it? We execed into the master node (vttablet-100) mysql container and did a usual mysql import but the vttablet pod kept crashin after sometime. The dump is 13Gb in size.
sougou
Can you look at the reason why the pod was terminated? Most likely, you ran out of some resource.
mshivanna
yeah i have increased the cpu its not failing quite often but its failing will increase again. will update here thank you @sougou
Ameet presents at Velocity conference, NY
ameet [Oct 2nd]
Hi Vitessians, I just finished my talk about Moving Slack's database to Vitess at Velocity Conference, NY. Here's the link to the talk and slides: https://conferences.oreilly.com/velocity/vl-ny/user/proposal/status/69885 The response was great. There was lots of interest about Vitess.
Improved control on resharding
young [Oct 5th]
Is there an open issue for encapsulating resetting vreplication in one command? It's quite annoying to do manually.
sougou
i'm wokring on a PR to perform high level commands for canceling resharding etc.
UPDATE: these features are now done.
Understanding keyspace ids and keyranges
Mark Solters [Oct 5th]
given a shard like 80-
what is the smallest keyspace ID that would be mapped to this shard?
is it 0x80? 0x81? 0x800? 0x8000?
(i am trying to construct a numeric_static_map)
i know that we use a syntax that makes the RHS zeros βoptionalβ but I also think that the center of the keyspace canβt be as small a number as 0x80. (!)
is what we write as 0x80 actually base-10 9223372036854775808?
sougou
the keyspace id is a bunch of bits (left justified)
there is theoretically no limit to the number of bytes it can have
it may get confusing if you try to see it as a number
because numbers are right justified
in some cases, we 'encode' a number as a keyspace id. If so, we set the length as 64 bits.
it's just a convention. One could have used 128 bits or 32 bits, or whatever.
Mark Solters
hmm, OK so how then does one construct a numeric_static_map?
the vitess repo contains a numeric_static_map_test.json where it is simply mapping some example primary keys to integers like 1 and 2, which if i'm reading this correctly, are the keyspace IDs
im basically confused about how this map here translates to shards: https://github.com/vitessio/vitess/blob/master/go/vt/vtgate/vindexes/testdata/numeric_static_map_test.json
{ "1": 1, "3": 2 }
sougou
Oops. Sorry about the tangent. Yeah. In your case, you're right. the 922.. number is the lowest number for shard 80-
this is because numeric_static_map converts the number into a 64-bit keyspace id.
Mark Solters
yes, and i take your point about the question being ambiguous without something grounding the bit size
hmmmm so, for this (trivial) example to work
i guess id have to construct a shard like -000000000000002
which would have an effective key size of 1
sougou
right. that shard can have 2 ids (0 & 1)
Meaning of target in the Go driver
derekperkins [Oct 5th]
@sougou what is a target in the go driver? https://github.com/vitessio/vitess/blob/master/go/vt/vitessdriver/driver.go#L129
sougou
best documentation is the test https://github.com/vitessio/vitess/blob/master/go/vt/vitessdriver/driver_test.go
derekperkins
ah, thanks
and leaving it empty presumably points to master?
sougou
yeah
well
if you didn't override the default tablet type in vtgate
File: content/en/blog/20181210-introducing-vitess-3.md
author: "Adrianna Tan" date: 2018-12-10T09:07:21-08:00 slug: "2018-12-10-introducing-vitess-3.0" tags: ['Major Versions, Announcements'] title: "Introducing Vitess 3.0"
We are pleased to announce Vitess 3.0, a major upgrade from Vitess 2.2. Every major release of Vitess brings new features and improvements for our community, and also sometimes introduces new ways of doing things.
Vitess 3.0 is built using βpureβ go 1.11 (we do not need cgo now) and supports MySQL 8.0 and MariaDB 10.3.
The key features of Vitess 3.0 are:
- Usability
- Simplified db parameters for vttablet
- Formal support for externally managed mysql
- More tutorials including how to run Vitess with Minikube
- Prometheus monitoring
- Performance improvements
- Snappier InitShardMaster and PlannedReparentShard
- Improved coordination with Orchestrator
- vtbench for benchmarking
- MySQL protocol performance improvements
- Faster reparents
- 4X faster parallelized backups
- Many more performance improvements
- VReplication
- Improvements to resharding
We first showcased VReplication at the first ever Vitess meetup held at Slack in July 2018. One of Vitessβs superpowers has always been its ability to consume the MySQL binary replication log, apply sharding logic to it, and use it for transparent resharding. Now we have taken the same functionality and made it composable so that it can be used for cross-shard materialized views. This enables exciting functionality such as roll-ups and aggregates, in quasi-real time (of the order of replication lag).
We are really excited about this and we see practical applications of VReplication such as:
- Companies ingesting large time-series data who would mostly need to query roll ups and aggregates
- All types of companies that want the flexibility to not worry about being stuck with their original sharding key. VReplication allows you the ability to make changes to your sharding key as your product evolves. In fact the internal name for this feature for a long time was βthe regret featureβ :).
As with any major version upgrade, we recommend that you follow our upgrading guide. Reach out to the Vitess community on our Slack channel (or click the Slack icon in the top right to join) at any time for assistance and discussion. We welcome everyone to our community.
Head on over to check out Vitess 3.0 now.
File: content/en/blog/2019-02-07-choosing-a-vindex.md
author: "Abhi Vaidyanatha" date: 2019-02-07T09:07:21-08:00 slug: "2019-02-07-choosing-a-vindex" tags: ['Guides', 'Vindexes', 'Documentation'] title: "Choosing a Primary Vindex"
When we talk to Vitess, it appears as if we are talking to a single unit, so what sets up this seemingly magical feature? This is achieved through a VSchema, the beautiful mind that sends all of your queries to the correct shard.
When Vitess shards your database, it assigns each row an identifier called a keyspace ID. We then break up the domain of all keyspace ID values into ranges and assign ranges to each shard. Therefore, if a rowβs keyspace ID falls in a certain range, it will be assigned a specific shard. This is cool because we can reshard the data completely without changing the keyspace ID at allβ¦ or your application knowing about it. The less your application has to know, the better.
Vindexes are maps from column values to keyspace ID. This map can be configured in many different ways, but a simple hash map works fine. Weβll decide what kind of map we want after we pick our vindex column.
Half the battle of designing a VSchema is choosing a strong primary vindex - youβve learned that vindexes map a column value to a keyspace ID, so what qualities are we looking for?
- Frequency in WHERE clause of queries
- Uniqueness (of the mapping function)
- Co-locating rows for joins
- Co-locating rows for single-shard transactions
- High cardinality
Letβs break this down. Uniqueness just means that a vindex will map a column value to only one keyspace ID (or none at all). Remember that all vindexes need to do is direct our queries to the correct shard, so itβs okay if another column value maps to the same keyspace ID - itβs Vitessβ job to figure that out.
Note: If a vindex maps a column value to a null keyspace ID, Vitess will simply error out or neutralize the query depending on the query type.
Co-location is a critical concept to understand and should heavily influence your sharding scheme. When Vitess performs operations on your keyspaces, you want as many of them to be isolated to a single shard as possible. This can be easily achieved by using the same primary vindex for multiple tables, as all rows tied to the same primary index will automatically be located in the same shard due to the uniqueness property of the vindex map.
Cardinality refers to the number of unique elements in the column. A high cardinality will produce a sufficiently large number of keyspace IDs, which will give you finer control for rebalancing load through resharding.
Naturally, if youβre using a primary key as your where clause for your highest QPS queries, you will likely be using this as your primary vindex.
Can I change the values of my primary vindex?
No. Vitess does not support updating primary vindex columns, even if it will stay within a shard. We donβt want something to pass in tests and fail in production; updating the vindex may result in a row having to move across shards.
Note: 99.9% of the time you want your primary vindex to have a pre-established map between column value and keyspace ID. This is referred to as a functional vindex. Conversely, a lookup vindex is one where a table association is created between values and keyspace IDs for fine-grained query optimization. These lookup vindexes that help Vitess speed up your queries are used as secondary vindexes so that we can avoid doing scatter-gathers on queries that donβt refer to the primary vindex.
Finally, after we have decided on our column value, we can settle on a map type. Vitess supports some predefined ones such as identities, md5 hashes, bit reversal, and others, but you can also define your own! For most cases, identities and md5 hashes work great, but there are some exceptions. While not common, certain use cases involving geolocation may warrant these custom defined vindexes. For example, when you want to co-locate information from a certain region or customer, you can create functions that take information from the columns and create the keyspace ID to have expected similar properties. This allows you to have finer grained control over your shard ranges.
If you have any other questions, check the article on it in our documentation or head on over to the Vitess Slack channel!
File: content/en/blog/2019-03-12-vitess-security-audit.md
author: "Adrianna Tan" published: 2019-03-12T07:15:00-07:00 slug: "2019-03-12-vitess-security-audit" tags: ['Security'] title: "Vitess Security Audit Results"
We are happy to announce that Vitess recently underwent a security assessment, funded by CNCF / The Linux Foundation.
In February 2019, the team from Cure53 performed tests in the following areas:
- system complexity
- cloud infrastructure
- source code auditing
- operating system interaction
- low-level protocol analysis
- multi-angled penetration testing
This independent security audit was performed on locally installed systems, as well as with a Kubernetes-based cluster. The auditors performed: (1) manual code auditing and (2) code-assisted penetration testing.
Here are some highlights.
βIn Cure53βs view, there is a clear intention and follow-through on
providing a secure system for scaling MySQL databases. This was achieved by keeping
the attack surface minimal and selecting the language suited for this implementation.
The auditors managed to reach wide-spanning coverage of all aspects pertinent to the
main repository of the Vitess software system. The most likely avenues for exploitation
were chosen and verified for resilience.β
βThe results of this Cure53 assessment funded by CNCF / The Linux Foundation certify
that the Vitess database scaler is secure and robust. This very good outcome is
achieved by limiting the attack surface, taking appropriate care of user-supplied input
with security-driven best practices, as well as - to a certain extent - the usage of the Go
language ecosystem.β
βWhile the results of this assessment are few and far between and may suggest some
kind of test limitations, they in fact prove that the Vitess team delivers on the security
promises they make.β
The auditors identified three areas of improvement for the Vitess team to work on. We thank Cure53, CNCF, The Linux Foundation and all project contributors for their assistance.
Click here to read the report in full.
File: content/en/blog/2019-04-01-vitess-at-gosv.md
author: "Adrianna Tan" published: 2019-04-01T07:15:00-07:00 slug: "2019-04-01-vitess-at-gosv" tags: ['events'] title: "Vitess at GoSV"
When Vitess started at YouTube back in 2010, it was designed to work in Googleβs Borg. As a result of that interesting bit of history (and the Google origin story), Vitess wound up being one of the earliest adopters of (a) Go and (b) Kubernetes.
At last weekβs GoSV meetup (organized by the indefatigable Aarti and Conrad; join their meetup to get the latest updates on other Go events in Silicon Valley), Vitess co-creator Sugu Sougoumarane shared background stories about Vitessβ origin story, why Go was selected, and how the teams working on Vitess and Go overlapped during their time at Google.
Some highlights from the talk:
Vitess was cloud native from the start (because of how it was designed to run in Borg). Vitess was ready for Kubernetes before 1.0
Stateful workloads not generally recommended in Kubernetes (as this Twitter discussion brings up), but Sugu made a point about Vitess's stateless vtgate component making changes quickly available; Vitess is used statefully in production traffic in Kubernetes environments by several companies
He also demonstrated VReplication, an upcoming Vitess feature that will benefit anyone who needs materialized views and rollups.
Hereβs a deck for you to find out more.
For a VReplication demo with audio and a transcript, check out Suguβs talk at QCon San Francisco 2018 (scroll through to the βdemoβ section).
For questions about VReplication and how it works, feel free to join the Vitess community (click here to join).
File: content/en/blog/2019-06-17-unsharded-vitess-benefits.md
author: "Abhi Vaidyanatha" date: 2019-06-17T09:07:21-08:00 slug: "2019-06-17-unsharded-vitess-benefits" tags: ['Guides', 'Unsharded', 'Benefits'] title: "The Benefits of Unsharded Vitess"
For many large companies seeking help with horizontal scaling, Vitess' value proposition is easily understood; running stateful workloads at astronomical scale is a hard problem that Vitess has boldly solved in the past. However, for businesses that aren't hitting the performance limitations of standard MySQL, it may seem difficult to justify placing seemingly complex middleware in your data path with no immediate reward. I'm here to show you why unsharded Vitess is not just a pre-optimization for future horizontal scaling - it provides many upgrades to the MySQL experience.
Restrict Toxic Queries
It is far too easy to write SQL queries that look simple, but are inefficient to execute at the database layer due to missing indexes or small logic mistakes. These toxic queries can easily be introduced in otherwise benign looking code changes, but their impact can be severe enough to bring down your application.
Thankfully, Vitess kills and rewrites dangerous queries to make sure that your database performance isn't due to application or user error. For example, we will add configurable limits to your OLTP queries, reducing the number of full table scans. If you have special toxic queries that are unique to your data path, you can make your own custom rules that fail them before they touch your database. Additionally, Vitess also protects your database from hot queries by reusing results and preventing identical requests from hitting your database at the same time.
Monitoring
Vitess includes a fairly extensive debug suite with variables that are set up to directly export for time-series monitoring. Vitess has direct support for Prometheus metrics and can be configured to use most types of pull or push based monitoring tools. In addition to the vast selection of exported variables, Vitess ships with built-in status dashboards that can allow you to oversee database performance without needing to add extra software to your stack.
Consistent Topology
Unlike stock SQL offerings, Vitess' topology is backed by a consensus-based metadata store, so you will always have a consistent view of your database, its replicas, and any read-only analytics replicas that you have created. Along with this comes a built-in control plane that can handle high-level operations such as reparenting, all displayed in a clean web GUI. Finally, Vitess was created to be highly-available; its control plane and topology store work together nicely to deploy your databases across multiple regions.
Connection Pooling
Most individuals who have tried to run stock MySQL likely understand that its memory usage is fairly unpredictable; you are often at the mercy of uncontrolled memory allocations and have to spend large amounts of time configuring connection buffers or overprovisioning memory to avoid performance failures. Instead of opening a new thread for every connection to the database, Vitess maps its lightweight connections to a small set of MySQL connections to shrink configuration time and vastly increase the amount of open connections.
Kubernetes Migration
Interested in migrating your MySQL databases into Kubernetes? Vitess was built for this. Don't take my word for it, check out this talk by notable Vitess user HubSpot on their migration story to Kubernetes.
File: content/en/blog/2019-09-03-why-250gb-shards.md
author: 'Morgan Tocker' date: 2019-09-03T09:07:21-07:00 slug: '2019-09-03-why-250gb-shards' tags: ['Guides'] title: 'Why does Vitess recommend 250GB per MySQL server?'
Vitess has an opinionated approach to database scalability. Some of those opinions have minimal controversy such as how durability should be provided via replication, but the one I find interesting is the 250GB per MySQL server recommendation.
Is this a physical MySQL Limit?
In short: no. By βphysical limitβ I mean is there a file format restriction that says databases can not be greater than 250GB?
The physical limit for InnoDB is 64TB per tablespace, and in the default configuration each table is its own tablespace. With table partitioning, this limit can be extended even further.
Is this a practical MySQL Limit?
In short: not necessarily. By βpractical limitβ, I mean does MySQL instantly break down when it hits 250GB in database size? It is not uncommon for practical limits to be reached before physical limits.
The answer to this depends a lot on the table structure (and query patterns). Take these scenarios for example:
Table A:
CREATE TABLE tablea (
id INT NOT NULL PRIMARY KEY auto_increment,
b DATETIME NOT NULL,
c VARBINARY(512) NOT NULL,
INDEX(b)
);Table B:
CREATE TABLE tableb (
id INT NOT NULL PRIMARY KEY auto_increment,
b DATETIME NOT NULL,
c VARBINARY(512) NOT NULL,
UNIQUE (c)
);.. they look almost identical right? Lets try and insert rows into them in 32 parallel threads for one hour:
INSERT INTO {tablename} (b, c) VALUES (NOW(), RANDOM_BYTES(512)), (NOW(), RANDOM_BYTES(512)), ..;<figcaption>Table A Insert Performance Over 1 Hour In one hour, I was able to insert 113 million rows. The insert performance was fairly consistent despite the final table size (93GB) being much larger than the InnoDB Buffer Pool (16GB). I suspect the initial sharp drop in performance is the SSDs write cache being exceeded.</figcaption><figcaption>Table B Insert Performance Over 1 Hour Insert performance dropped as the table got larger. The 16GB buffer pool was not enough to hold all the important pages, and iostat showed a high number of reads/s as pages needed to be read-modify-written. The final number of inserted rows was 29 million, with a 50GB table size.Why do these two tables perform so wildly different?
The index on c is wider (512 bytes vs. 6 bytes), but the random insertion combined with uniqueness is the real performance killer over time.
With Table A, the performance is stable and consistent because the inserts are to the end of the table and the required pages are in memory. I repeated the benchmark with a 128MB buffer pool and observed only a 13% decrease in performance:
<figcaption>Table A Insert Performance Over 1 Hour (128M Buffer Pool) The total number of rows after 1 hour was 100 million. This represents only a 13% difference from the test using a 16GB buffer pool (compared closer in next chart).</figcaption><figcaption>Table A 128M vs. 16M buffer pool</figcaption>With Table B, insert performance is not sustained during the run time of the benchmark. Because the insert pattern on the unique index is random, there is no guarantee that the required index pages are in memory. But those pages must be loaded to make sure that a constraint check is not violated (column c must be unique).
So it is fair to say that the workload on Table B requires a higher memory fit than the workload on Table A. We could also improve performance by switching from RANDOM_BYTES(512) to something that is more insert efficient but still 512 bytes:
SELECT LENGTH(CONCAT(current_timestamp(6), RANDOM_BYTES(486)));
+---------------------------------------------------------+
| LENGTH(CONCAT(current_timestamp(6), RANDOM_BYTES(486))) |
+---------------------------------------------------------+
| 512 |
+---------------------------------------------------------+
1 row in set (0.00 sec)Converting to Insert Efficient
By prepending the random bytes with 26 bytes of a timestamp, the value becomes insert efficient. With our 16GB buffer pool we now have a very low rate of read-modify-write and can sustain performance as the table grows.
<figcaption>Comparing inserts per second performance between βinsert efficientβ and random values for c. Higher is better. Notice how insert efficient sustains performance as the table becomes larger.</figcaption>How far can an efficient inserts scale?
Table A only lost 13% of its insert performance when the buffer pool was lowered from 16GB to 128MB. To prove that there is not a clear βmaximum number of rowsβ limit, let's now extend the test run time to 5 hours. After inserting almost 463 million rows, we can see our 376GB table still retains most of its insert performance:
<figcaption>Performance is sustained while inserting for 5 hours. At 463 million rows, there is only an 18% drop from the 113 million rows inserted in 1 hour. Internally InnoDB uses pages to store, and the buffer pool cache is page oriented. There is no immediate supporting evidence that there is a row-count limit on table size.</figcaption>Insert performance is not limited by data size, or number of rows. It is dependent on the table+index structure, and how rows are inserted. It is really difficult to provide a generalized answer here. You could have a 256GB database that works well with 1GB RAM, and another 256GB database that requires 128GB RAM.
Okay, why the limit?
The example in the previous section described insert performance to illustrate a point. But performance is not limited to insert performance :-) Specifically, some management tasks become more difficult with larger databases:
- Taking a full backup
- Provisioning a new read replica
- Restoring a backup
- Making a schema change
- Reducing replica delay
Let's use a 4TB shard failure as an example:
- When the master fails, the blast radius will be much larger, potentially taking more of the service offline.
- When a replica fails, it will likely take 10-12 hours to restore a new replica at gigabit network speed. While this time can be reduced with a higher speed network (recommended); there is a fairly large window for a secondary failure could occur. Many Vitess users aim for 15 minute recoveries; which is possible with a 250G shard on a 2.5Gbps network.
Vitess does not impose 250GB as a hard limit. It even encourages you to run multiple instances of MySQL (multiple tablets) on the same host.
Conclusion
By specifying a recommended size, the authors of Vitess can also make assumptions about how long certain operations should take and simplify the design of the system. Or to paraphrase: the Vitess authors decided against a one-size-fits-all approach to scalability, and looping back to my opening sentence: Vitess has an opinionated approach to scalability.
TL;DR: Vitess suggests 250G as a shard size for management and predictable recovery times. It may be true for performance reasons too, but that depends a lot on your usage.
Test Disclosure
- 8 Core (16 thread) Ryzen 1700
- 64GiB RAM (MySQL intentionally limited with O_DIRECT)
- Samsung EVO 970 1TB
- Ubuntu 19.04
- MySQL 8.0.17
- MySQL Config:
- innodb-buffer-pool-size= 16G (modified to 128M in second Table A test)
- innodb-flush-method=O_DIRECT
- innodb-log-file-size=4G
- innodb-io-capacity=2000
- innodb-io-capacity-max=5000
- binlog_expire_logs_seconds=30
- skip-mysqlx
- max-binlog-size=100M
- Benchmark inserts in 32 threads (gist)
File: content/en/blog/2019-11-05-vitess-4.0-has-been-released.md
author: 'Sugu Sougoumarane, Morgan Tocker' date: 2019-11-05T07:50:21-07:00 slug: '2019-11-05-vitess-4.0-has-been-released' tags: ['Guides'] title: 'Vitess 4.0 has been released!'
Head to the release notes for an overview of functionality added or changed, as well as important changes for those upgrading from earlier releases.
We wanted to use this post as an opportunity to reflect on three aspects of Vitessβ development, as it has evolved from an internal project at YouTube to a CNCF project with almost 200 contributors.
Improved SQL Query Support
Vitess 4.0 takes a big leap forward in improving the coverage of MySQL syntax that is supported. Vitess can now support bulk statements, such as an insert that may need to cross shard boundaries.
A broader range of SELECT statements is also supported, including support for distinct aggregate queries such as COUNT(DISTINCT β¦). You can also modify Vitess itself via SQL with ALTER VSCHEMA.
We have also started testing Vitess with common applications and frameworks, and adding failures to our test suite. The goal is to make it possible to move from a monolithic MySQL or MariaDB to sharded Vitess, without the application having to know about it.
Improvements to Usability
Vitess was created to solve a major challenge - scaling the databases of YouTube during its massive growth. In solving YouTube's needs, Vitess also added a number of features that help you run databases better in production. The downside however, is that with internal development there is not always enough focus on the onboarding experience of new users.
With Vitess 4.0, we have worked on several initiatives to make it easier for new users:
- Weβve worked on refining the getting started tutorials for local development, Kubernetes and Vagrant.
- Less configuration is required to get started, as the MySQL version can in many cases be auto-detected.
- A number of error messages have been refined, and focus has been placed on making sure they are at the correct log-level (error, warning or info).
This will continue to be a focus as we head into the development of Vitess 5.0.
Experimental Support for VReplication
One of the downsides of sharding is that you can be forced to make trade-offs. For example in an ecommerce platform where you have buyers and sellers, you could choose to shard by buyers, in which case querying by seller in the sharded system may become much slower.
For applications that need to query efficiently by both buyer and seller, VReplication provides a way to subscribe to changes made on each shard (using the MySQL binary log), and keep redundant copies of key data available on other shards. You can think of this feature as similar to materialized views available in other commercial databases.
Looping back to SQL support, Vitess 4.0 also supports the concept of table equivalence. This means that you can instruct Vitess to read from either the original table or the VReplication materialized view: whichever makes the query execute faster.
--
This was just a quick overview of some of the new features in Vitess 4.0, but again we encourage you to check out the release notes which go into additional detail.
Starting with Vitess 5.0 we will be transitioning to a 12 week release cycle. We welcome your contributions. Please check out the open issues in vitessio/vitess and vitessio/website (docs) and join the Vitess slack channel.
File: content/en/blog/2019-mysqlcontributoraward.md
author: "Adrianna Tan" published: 2019-04-29T07:15:00-07:00 slug: "2019-04-29-mysql-community-contributor-award" tags: ['mysql, oracle, vitess'] title: "2019 MySQL Community Contributor Award Program"
Building the Vitess community has been our pride and joy. Being able to contribute to the MySQL community, even more so. Vitess' Sugu Sougoumarane has been nominated by the MySQL group for Oracle's 2019 MySQL Community Contributor Award Program, where he joins folks like Shlomi Noach, Peter Zaitsev, Gabriela D'Γvila Ferrara, Giuseppe Maxia and many other active MySQL community members recognised for their contributions to MySQL.
Criteria for the nominations included: most active code contributor, bug report,most active MySQL blogger, people who play an active role in translating or documenting MySQL articles, people who provide feedback on DMR releases, Labs release, or change proposal, as well as anyone in the community who did really useful work that ought to be thanked publicly.
To view the full list, head over to the blog post to find out more.
File: content/en/blog/2020-01-14-vitess-graduation-retrospective.md
author: "Abhi Vaidyanatha" date: 2020-01-14T09:09:21-08:00 slug: "2020-01-14-vitess-graduation-retrospective" tags: ['graduation', 'vitess graduation'] title: "Vitess Graduation Retrospective"
Last November, Vitess became the eighth CNCF project to reach graduation, joining a host of amazing projects such as Kubernetes, Prometheus, Envoy, CoreDNS, containerd, Fluentd, and Jaeger. To contextualize this milestone, I picked some tidbits from the brain of Vitess co-creator, Sugu Sougoumarane, allowing him to share internal perspective about how we got here, the hurdles we faced, and where weβre headed.
Incubation
Considering that it was only the February of 2018 when the CNCF agreed to host Vitess as an incubating project, Vitess has made efficient strides toward becoming the de-facto standard for horizontally scaling MySQL. Beyond horizontal scale, however, our main goal for Vitess on its acceptance to the CNCF was to spearhead the ability to run databases in Kubernetes. We're very excited at the progress weβve made as a community and these juxtaposed quotes from Slack principal engineer, Michael Demmer, show the evolution of the project firsthand:
| Michael Demmer on Vitess incubation (2/5/2018) | Michael Demmer on Vitess graduation (11/5/2019) |
|---|---|
| βSlack is in the midst of a major migration of the MySQL infrastructure at the core of our service, driven by the need for an architecture that scales to meet the growing demands of our largest customers and features under the pressure to maintain a stable and performant service that executes billions of MySQL transactions per hour, said Michael Demmer, Senior Staff Engineer at Slack. βWe needed a solution that would offer a familiar full featured SQL interface, and wanted to continue to use MySQL as the backing store to maintain our operations knowledge and comfort level. Vitess is a natural choice for this purpose and has served us well so far.β | βVitess has been a clear success for Slack,β said Michael Demmer, principal engineer at Slack. βThe project has both been more complicated and harder to do than anybody could have forecast, but at the same time, Vitess has performed in its promised role a lot better than people had hoped for. Our goal is that all MySQL at Slack is run behind Vitess. Thereβs no other bet weβre making in terms of storage in the foreseeable future.β |
Post-Incubation
After beginning incubation, there was some speculation around whether Vitess would keep up with the rigorous requirements of the open source community in the areas of security and continuous integration. Sugu, however, wasnβt so scared:
Given that Vitess is being continuously used in security-sensitive production environments like YouTube, Squareβs Cash App, and Slack, it wasnβt a surprise that no material vulnerabilities were found. Another area of high scrutiny was related to diversity of employers among contributors. This wasnβt a challenge either; Vitess adopters deeply care about the project and have been continuously investing time and effort. We now have 14 active maintainers from many different companies.
Preparing for Graduation
With the continued support of our open source maintainers and contributors, it slowly became obvious that Vitess had naturally reached the graduation requirements without directly trying. Suguβs confidence continued into this period, as he believed that graduation was mostly a formality at this point. While many shared his confidence, the graduation process had changed since the last graduating project.
The formal process starts with a Pull Request on the TOC repository with answers to the Graduation Criteria. As mentioned before, the incubation criteria had evolved since February 2018 (and in some respects, some of the incubation criteria are harder to meet). To accommodate for this, we included answers for both versions of the criteria. After our requirements were verified, we were given a date to present to the TOC. Even after verification, we had one more test to pass; a due diligence checkup from a TOC member.
Due Diligence
While getting past this stage is no easy feat, the review came down to four things: quality, adoption, contribution, and support. While adoption, contribution, and community support came down to statistics, displaying quality proved to be slightly harder.
We started with an outline of common questions we assumed that individuals would like to know about a database project, but it came down to these two: how do you test it, and how do you ensure performance? The reviewer, rightfully so, asked for clearer answers on this, making us expound on the ways that Vitess compares to other technologies that occupy a similar role. Additionally, we were more than happy to dive into details about adoption, maintainership, and the design process for new features with our reviewer, who was interested in all of these things and more. Above all else, Sugu seemed to be focused on appreciating the review:
It was all good feedback. I think this will be an interesting line in the sand to see where Vitess is as we continue development moving forward.
Where Are We Now?
| Vitess Project Stats (2/5/2018) | Vitess Project Stats (11/5/2019) |
|---|---|
From both the bustling community and the development of the project, itβs fairly clear that Vitess is continuing to gain momentum. The number of Vitess adopters and people running on Kubernetes is on the rise, a correlation that we predict will remain positive. Vitess is now is a pioneer in showing that one can indeed run stateful workloads in Kubernetes, a statement that many are quick to dismiss. With major companies committing to fully migrating to Vitess, it has emerged as one of the most trusted storage solutions in the cloud native space.
*If youβre moving to Kubernetes, donβt leave your data behind.*
Where Are We Going?
While our feature offering has continued to serve the public well, we are aware that getting on board with the product is not as straightforward as weβd like it to be. One of our principal focuses going forward is making Vitess more and more approachable. On this topic, Sugu is hopeful for the future:
Bringing up a Vitess cluster shouldnβt be hard, and weβre going to make it extremely easy to do so. At the same time, making the migration path simpler for our users that want a drop-in replacement for MySQL will be pivotal to accelerating adoption.
If you are interested in joining the ever-growing force of Vitess contributors, make sure to check out our community Slack to get started!
File: content/en/blog/2020-02-05-announcing-the-release-of-vitess-5.0.md
author: 'Morgan Tocker' date: 2020-02-04T08:00:21-07:00 slug: '2020-02-04-announcing-the-release-of-vitess-5.0' tags: ['Guides'] title: 'Announcing the Release of Vitess 5.0'
On behalf of the Vitess maintainers team, I am pleased to announce the immediate release of Vitess 5.0.
Vitess 5.0 is largely a clean up release, where we have both deprecated and removed some minor features, and improved both the installation experience and health of the Vitess code-base.
When upgrading from a previous release of Vitess, we recommend reading the Incompatible Changes highlighted in the release notes for both 5.0 as well as Beta 0 and Beta 1.
File: content/en/blog/2020-04-27-life-of-a-cluster.md
author: "Sugu Sougoumarane" date: 2020-04-27T20:30:00 slug: "2020-04-27-life-of-a-cluster" tags: ['vitess', 'vitess cluster', 'vitess troubleshooting', 'vitess getting started'] title: "Life of a Vitess Cluster"
This post goes into the details of what goes on behind the scenes when a cluster is brought up, for example using helm or the local installation guide. This can be used both as a learning tool and troubleshooting guide. We assume that you have downloaded and installed all the necessary binaries before proceeding further.
Vitess is a very flexible system that is capable of running in a variety of environments. The local example does oversimplify things a bit. However, you will need to take more things into consideration when taking Vitess into production.
It will also be important to know how the various components interact with each other. This knowledge will facilitate troubleshooting if a cluster does not come up as intended.
Choosing a Topology Server
The first component one needs to bring up is actually not a Vitess component. The toposerver can be ZooKeper, etcd, consul, or Kubernetes. Vitess needs a topo server to be up and running. The steps needed to bring up every kind of toposerver are not covered here.
Once you bring up the TopoServer, make sure that you can connect to it using one of their clients.
Choosing a Topo root
You will probably need to run multiple independent Vitess clusters. For example, you may want to separate out the testing and staging clusters from the production one. However, you may still want to reuse the same TopoServer for all of these.
For this reason, Vitess allows you to choose a root directory in the Topo for each cluster. This directory is known as the topo_global_root and will need to be provided for every Vitess binary that is launched.
Caveat: In the case of ZooKeeper, you will actually need to create this directory in the server.
In the local example, we have chosen this to be /vitess/global. Here is a sample command to bring up etcd:
ETCD_SERVER="localhost:2379" etcd \
--enable-v2=true \
--data-dir="${VTDATAROOT}/etcd/" \
--listen-client-urls="http://${ETCD_SERVER}" \
--advertise-client-urls="http://${ETCD_SERVER}"Configuring vtctld
The most important flags for vtctld are the parameters needed to connect to the TopoServer and -topo_global_root. Here is a sample vtctld invocation:
vtctld \
-topo_implementation=etcd2 \
-topo_global_server_address=localhost:2379 \
-topo_global_root=/vitess/global \
-port=15000 \
-grpc_port=15999 \
-service_map='grpc-vtctl'If the TopoServer is unreachable, or if the topo_global_root is not specified, vtctld will fail to start. You should see the following error message in the logs:
F0426 11:11:40.363545 14833 server.go:223] Failed to open topo server (etcd2,localhost:2379,/vitess/global): dial tcp 127.0.0.1:2379: connect: connection refusedOther required parameters to vtctld are port, grpc_port and service_map 'grpc-vtctl'.
The service_map flag allows you to configure the grpc APIs that a Vitess server exposes as gRPC. If grpc-vtctl is not specified as a service_map for vtctld, you will not be able to access it using vtctlclient.
Creating a cell
The next step is to create a cell. This can be done by issuing the following command:
vtctlclient AddCellInfo -root=/vitess/zone1 -server_address=<address> zone1NOTE: vtctlclient does not need a topo global root, because it only talks to vtctld, and vtctld already has that value.
The β-rootβ flag is different from topo_global_root. All information specific to the cell will be stored under /vitess/zone1. The metadata about the cell (the fact that zone1 data is in /vitess/zone1) is stored in the global topo. Vitess binaries fetch this information from the global topo before switching to use the cell topo.
For higher fault tolerance, you can set up and specify a different TopoServer to serve the local cell. If isolation of failure zones is not important, you could just reuse the main TopoServer as long as you ensure that the root paths donβt conflict.
For the best fault tolerance, you'll need to setup the global topo server such that its nodes are distributed across multiple zones. The nodes of the local topo server should be within the cell itself.
The last parameter βzone1β is the name of the cell, which is required by the subsequent tools.
You can verify this information by browsing the Topology in vtctld:
Note: In the local example, weβre using the vtctl tool to create the local cell. This is because we are creating the local cell before bringing up vtctld. However, this is not necessary. You can create the local cell after bringing up vtctld.
At this point, we have officially created an empty Vitess cluster.
Configuring VTGate
Although the local example brings up vtgate last, this is not necessary. You can bring up vtgate before creating any keyspaces or bringing up vttablets. VTGate will discover them as they are brought up.
In addition to the topo parameters, vtgate requires a cell to operate in. A vtgateβs main job is to forward requests to the vttablets in the local cell. However, vtgates can go cross-cell in two situations:
- vtgate receives queries to the master, and the master is not in the current cell.
- vtgate was configured to go to other cells in case no local vttablets were available.
For sending master queries across cells, you must specify an additional cells_to_watch flag. This will make the vtgates watch those additional cells, and will help them keep track of the masters in those cells.
The cells_to_watch flag is a required parameter and must at least include the current cell. This is an issue weβll fix soon: https://github.com/vitessio/vitess/issues/6126.
Going cross-cell for non-master requests is an advanced use case that requires setting up cell aliases, which will not be covered here.
The port flag is mandatory for vtgate.
For those who wish to use the Java or Go grpc clients to vtgate, you must also configure grpc_port and specify the service map as service_map='grpc-vtgateservice'.
For those who wish to use the mysql protocol, you must specify a mysql_server_port and a mysql_auth_server_impl for configuring authentication.
Here is a sample vtgate invocation:
vtgate \
-topo_implementation=etcd2 \
-topo_global_server_address=localhost:2379 \
-topo_global_root=/vitess/global \
-cell=zone1 \
-cells_to_watch=zone1 \
-port=15001 \
-grpc_port=15991 \
-service_map='grpc-vtgateservice' \
-mysql_server_port=$mysql_server_port \
-mysql_auth_server_impl=noneThe reason why the local example brings up vtgate last is because vtgate polls the TopoServer for changes. Bringing it up last allows vtgate to find all the vttablets that were brought up, and immediately ready itself to send requests to them. This polling frequency is controlled by the tablet_refresh_interval whose default value is one minute. This means that it may take up to one minute for vtgate to discover a new vttablet that has come up. This interval can be lowered. However, one must be careful to ensure that too many vtgates donβt overwhelm the TopoServer.
VTGate uses the global topo to get the topo addresses of the cells it has to watch. For this reason, you do not need to specify the topo addresses for the individual cells.
VTGate does not communicate with vtctld.
A vtgate that comes up successfully will show all the vttablets it has discovered in its /debug/status page under the Health Check Cache section.
If vtgates cannot connect one of the vttablets it discovered to from the topo, or if the vttablet is unhealthy, it will be shown in red in the Health Check Cache, and a corresponding error message will be displayed next to it:
Understanding Keyspaces and Shards
You can create keyspaces and shards using vtctlclient commands. However, they are not necessary because these are implicitly created as you bring up the vttablets.
Itβs important to be aware of the relationship between the global topo and the cell-specific topo. The canonical information for keyspaces and shards is created in the global topo. This information is then pushed to the cell-specific topos through rebuild commands like RebuildKeyspaceGraph and RebuildVSchemaGraph. These commands are implicitly issued on your behalf whenever applicable. But there are situations where youβll have to issue them manually. For example, if you create a new cell, youβll have to issue these commands to copy the data into the new cell.
There are use cases where you may want to experimentally deploy changes to only some cells. Separating information from the global topo and local cells makes those experiments possible without affecting the entire deployment.
Tools like vtgate and vttablet consume information from the local copy of the topo.
An unsharded keyspace typically has a single shard named 0 or -. A sharded keyspace has shards named after the keyranges assigned to it, like -80 and 80-. The following section describes the process of bringing up vttablets for a single shard.
Configuring VTTablets
For the sake of durability, we generally recommend that you bring up a quorum of vttablets coupled with their MySQL instances. Itβs recommended that you bring up at least three vttablets, with semi-sync replication enabled. To bring up each node, perform the following steps:
1. Starting MySQL
In order to bring up mysql, you may use the mysqlctl convenience wrapper. This tool is capable of bringing up multiple isolated mysql instances within a single machine, and preconfiguring them for easy connectivity from a vttablet.
The necessary arguments to a mysqlctl are the tablet_uid and mysql_port. This tablet UID should be supplied as tablet-path when invoking vttablet. Hereβs a sample invocation:
mysqlctl -tablet_uid zone1-100 -mysql_port 17100 initThere is a common pitfall to watch out for: If you see an error like this in the mysqlctl logs, you may need to disable AppArmor:
I0429 01:16:25.648506 1 mysqld.go:454] Waiting for mysqld socket file (/vtdataroot/tabletdata/mysql.sock) to be ready...
I0429 01:16:25.656153 1 mysqld.go:399] Mysqld.Start(1588122985) stderr: mysqld: [ERROR] Could not open required defaults file: /vtdataroot/tabletdata/my.cnf
I0429 01:16:25.656180 1 mysqld.go:399] Mysqld.Start(1588122985) stderr: mysqld: [ERROR] Fatal error in defaults handling. Program aborted!
I0429 01:16:25.657249 1 mysqld.go:418] Mysqld.Start(1588122985) exit: exit status 1Note that disabling AppArmor once may not be enoug. Many software installs or upgrades automatically install it back. You may have to disable it again if this happens.
Ensure that MySQL came up successfully. Because the full initialization of MySQL will be done after the vttablets come up, expect to see errors like these in the log file:
2020-04-27T00:38:02.040081Z 2 [Note] Aborted connection 2 to db: 'unconnected' user: 'root' host: 'localhost' (Got an error reading communication packets)The MySQL instance that was brought up has no identity related to keyspace or shard at this moment. These will be assigned in the following steps.
Starting VTTablets
VTTablet needs the topo and cell flags. Additionally, it needs the following flags:
tablet-path: This should be the same as thetablet-uidthat was supplied to the mysqlctl command.init_keyspace: The keyspace that the tablet is going to serve. This will cause a keyspace to be created if one is not present.init_shard: The shard that the tablet is going to serve. This will cause a shard to be created if one is not present.init_tablet_type: This will typically beREPLICA. You may use other tablet types like βRDONLYβ. Those tablet types will be deprecated in favor of newer ways to achieve their functionality. Note that you are not allowed to start a tablet as aMASTER.enable_semi_sync: The recommended value for this isTRUE. You will need to bring up at least three vttablets for this setting to work correctly.port,grpc_port, and-service_map 'grpc-queryservice,grpc-tabletmanagerβ
You will typically need additional parameters for setting up backups and automatic restores, which weβll not cover here. Here is a typical example:
vttablet \
-topo_implementation=etcd2 \
-topo_global_server_address=localhost:2379 \
-topo_global_root=/vitess/global \
-cell=zone1 \
-tablet-path=zone1-100 \
-init_keyspace=commerce \
-init_shard=0 \
-init_tablet_type=replica \
-enable_semi_sync=true \
-port=15100 \
-grpc_port=16100 \
-service_map 'grpc-queryservice,grpc-tabletmanagerβBringing up the first vttablet will cause the keyspace and shard to be created in the global topo. Also, this action will cause a topology rebuild that will ensure that this information is propagated to the current cell.
Additionally, the vttablet will create a βtablet recordβ in the cellβs topo, which will be observed by the vtgates. The vtgate will then make a connection to the vttablet and will establish a health check stream. This is what causes the tablet to show up in vtgates Health Check Cache section.
However, visiting the vtgate page at this time will show all these tablets as unhealthy:
One final step is needed to get them started.
Starting InitShardMaster
The InitShardMaster step initializes the quorum by electing a master and setting up replication for the replicas. Additionally, a database is created to store the data for the keyspace-shard. The command is as follows:
vtctlclient InitShardMaster -force commerce/0 zone1-100NOTE: If you have semi-sync enabled and did not set up at least three replicas, InitiShardMaster could hang indefinitely. Even if it succeeds, future operations that perform failovers could cause this shard to go into a deadlocked state. The local example sets up only two replicas mainly to minimize resource usage.
After this step, visiting the /debug/status page on vtgate should show these tablets as green.
Congratulations! You have successfully brought up a Vitess cluster.
Whatβs next
The above steps explain in detail the β101β step of the example. Following this, you will need to upload a schema and a VSchema. This will be covered in a different user guide.
File: content/en/blog/2020-04-29-announcing-vitess-6.md
author: 'Morgan Tocker' date: 2020-04-29T08:00:21-07:00 slug: '2020-04-29-announcing-vitess-6' tags: ['Guides'] title: 'Announcing Vitess 6'
I am excited to announce the general availability of Vitess 6, the second release to follow our new accelerated release schedule.
While only 12 weeks have elapsed since the previous release, it feels like a few key investments have started to pay dividends all at once. To provide some personal highlights:
Improved SQL Support
Vitess now understands much more of MySQLβs syntax. We have taken the approach of studying the queries issued by common applications and frameworks, and baking them right into the end-to-end test suite.
Common issues such as SHOW commands not returning correct results or MySQLβs SQL_CALC_FOUND_ROWS feature have now been fixed. In Vitess 7, we plan to add support for setting session variables, which will address one of the largest outstanding compatibility issues.
Kubernetes Topology Service
The Helm charts now default to using Kubernetes as the Topology Service. This helps remove a dependency on etcd-operator, which has since been discontinued.
This change also unlocked the adoption of Helm 3 and support for a wider range of Kubernetes versions, making installing Vitess much easier.
General Availability of VReplication-based Workflows
While VReplication made its appearance in Vitess 4, it has now been promoted from experimental to general availability and the documentation now points to MoveTables and Resharding.
These workflows require significantly fewer steps than their predecessors (Vertical Split Clone and Horizontal Sharding), of which we intend to deprecate at some point in the future.
--
In addition to this, the end-to-end testsuite is now fully migrated to Golang, and weβve improved the health of the code base by removing a lot of legacy code specific to Statement-Based Replication and βV2β query routing.
There is a slightly higher number of incompatible changes than in prior releases, so we encourage you to spend a moment reading the release notes.
Please download Vitess 6, and take it for a spin!
File: content/en/blog/2020-05-26-vitess-cross-cell.md
author: "Pratik Gupta" date: 2020-05-26T11:20:00 slug: "2020-05-26-vitess-cross-cell" tags: ['vitess', 'vitess cluster', 'vitess cross-cell', 'vitess getting started'] title: "Vitess: The Cross Cell Connection"
This post explains about how VTGate handles cross-cell operations and how to configure CellAlias for cross-cell read operations.
If you are new to Vitess, it is recommended to read this blog post to get more familiar with the various components and their configuration in Vitess.
To understand CellAlias, first let's get familiar with what a cell means in Vitess. A cell is a group of servers and network infrastructure collocated in an area, and isolated from failures in other cells. It is typically either a full data center or a subset of a data center, sometimes called a zone or availability zone. Vitess gracefully handles cell-level failures, such as when a cell is cut off the network.
By default Vitess limits cross-cell traffic by only routing the writes to a master if it does not reside in the current cell. Vitess will always prefer the replicas in the current cell for all read operations.
However in some cases it may be necessary to route read operations to different cells eg. when all the replicas in the current cell fail. For all such cases, we need to configure CellAlias.
CellAlias
A CellAlias defines a group of cells within which replica/rdonly traffic can be routed across cells. By default, Vitess does not allow replica traffic between different cells. Between cells that are not in the same group (alias), only master traffic can be routed.
Here is a sample command for creating a CellAlias:
vtctl \
-topo_implementation=etcd2 \
-topo_global_server_address=localhost:2379 \
-topo_global_root=/vitess/global \
AddCellsAlias \
-cells zone1,zone2 \
cellglobalHere zone1 and zone2 are two cells in different datacenters and cellglobal is the alias name.
Configuring VTGate
Although we do not need to pass the CellAlias name directly to VTGate, we do need to pass all the cell names that are part of the CellAlias using the -cells_to_watch flag.
VTGate will be able to route read queries to all cells that it is watching which also belong to the same cellAlias as vtgate's local cell (-cell flag).
Here is a sample command for setting -cells_to_watch flag in VTGate:
vtgate \
-topo_implementation=etcd2 \
-topo_global_server_address=localhost:2379 \
-topo_global_root=/vitess/global \
-cell=zone1 \
-cells_to_watch=zone1,zone2 \
-port=15001 \
-grpc_port=15991 \
-service_map='grpc-vtgateservice' \
-mysql_server_port=$mysql_server_port \
-mysql_auth_server_impl=noneUnderstanding VTGate Cross-Cell Behaviour
- VTGate will always be able to route to a master in a different cell (which is part of cells_to_watch) even without a cellAlias. the cellAlias requirement is only for replicas.
- By default VTGate sends all queries(reads and writes) to the master.
- Replica reads can be performed by first issuing a
use ks@replicawhereksshould be replaced by your keyspace name. - VTGate will always prefer tablets that are in the same cell over tablets in other cells despite the CellAlias.
- VTGate caches the CellAliases from the Topology Server, so if an alias is created/updated after the VTGate instance has been started then VTGate must be restarted to fetch the CellAlias. This behaviour is similar to adding/removing new cells where the VTGate instances need to be restarted to udpate the
-cells_to_watchvalues.
File: content/en/blog/2020-07-28-announcing-vitess-7.md
author: 'Deepthi Sigireddi' date: 2020-07-28 slug: '2020-07-28-announcing-vitess-7' tags: ['release'] title: 'Announcing Vitess 7'
On behalf of the Vitess maintainers team, I am pleased to announce the general availability of Vitess 7.
Major Themes
Improved SQL Support
We continued to progress towards (almost) full MySQL compatibility. The highlights in Vitess 7 are replica transactions, savepoint support, and ability to set system variables per session.
We expect to continue down this path for Vitess 8.
Stability
Vitess had significant technical debt because of functionality that has been added organically. Some parts of the code had become unmaintainable.
In this release, VTGate's healthcheck and VTTablet's tabletserver and tabletmanager have been rewritten.
The rewrites have already paid dividends. Replica transaction support and system variable support are built on the foundation of the new healthcheck and tabletserver.
VTTablet rewrites are expected to facilitate several new features in upcoming releases.
Innovation
Vitess 7 adds ease-of-use and many new features built on top of VReplication. VStream Copy allows streaming of entire tables or databases, thus enabling change data capture applications.
Schema Versioning enables correct handling of binlog events on replication streams based on older versions of the schema.
VExec and Workflow commands make it possible to manage vreplication workflows without manual edits to metadata.
A novel framework has been built to allow dedicated connections alongside connection pooling. Locks and system variables have been implemented using this.
Tutorials
Vitess 7 adds three new tutorials to the documentation. We have added a tutorial that demonstrates how to use the open source vitess-operator from PlanetScale,
a tutorial for region-based sharding, and one for a local docker installation.
There is a short list of incompatible changes in this release. We encourage you to spend a moment reading the release notes.
Please download Vitess 7 and try it out!
File: content/en/blog/2020-10-27-announcing-vitess-8.md
author: 'Alkin Tezuysal' date: 2020-10-27 slug: '2020-10-27-announcing-vitess-8' tags: ['release'] title: 'Announcing Vitess 8'
On behalf of the Vitess maintainers team, I am pleased to announce the general availability of Vitess 8.
Major Themes
In this release, we have continued to make important improvements to the Vitess project with over 200 PRs in several areas. Some of the major bug fixes and changes in behaviors are documented in the Release Notes. Please read them carefully and report any issues via GitHub. We would like to highlight the following themes for this release.
Compatibility (MySQL, frameworks)
Our ongoing work to make sure that Vitess accepts all queries that MySQL accepts. In particular, work has focused on SET and information_schema queries. Reserved connections are still not on by default, and you might need to enable it to see all queries and frameworks well supported.
We are proud to announce that we have initial support for:
- PHP
- WordPress
- Mysqli
- JavaScript
- TypeORM
- Sequelize
- Python
- Django
- PyMySQL
- SQLAlchemy
- Ruby
- Rails/ActiveRecord
- Java
- JDBC
- Hibernate
- Rust
- MySQL
- mysql_async
- SQLx
- Tooling
- MySQL Workbench
- Mycli
Migration
Performance and error metrics and improved logging related to VReplication workflows have been added for more visibility into operational issues. Additional vtctld commands VExec and Workflow allow easier inspection and manipulation of VReplication streams.
The VStream API was enhanced to provide more information for integration with change data capture platforms: the Debezium Vitess adapter uses this capability.
We have incorporated several small feature enhancements and bug-fixes based on the increased traction that VReplication saw both among early adopters and large production setups.
Usability
Ease of usability and accessibility are very important for the Vitess community. Usability improvements were another highlight received from the community.
Innovation
We continue to add integration of popular open-source tools and utilities on top of the Vitessβs dynamic framework. There are a few of these in this release we would like to highlight.
- VTorc : Integration of Orchestrator has continued and finally became part of Vitess. This proven open-source tool which has been the de-facto solution for MySQL failover mechanisms is now built into Vitess. Support is experimental in 8.0 and we will continue to harden it in future releases.
- Online Schema Changes: Understanding the ALTER TABLE problem and coming up with a solution using proven tools was our goal to achieve this release. Weβre able to integrate both pt-online-schema-change and gh-ost to overcome major limitations for schema migrations.
There is a shortlist of incompatible changes in this release. We encourage you to spend a moment reading the release notes.
Please download Vitess 8 and try it out!
File: content/en/blog/2020-11-03-streaming-vitess-at-bolt.md
author: 'Kewei Shang' date: 2020-11-03 slug: '2020-11-03-streaming-vitess-at-bolt' tags: ['Vitess','MySQL','Debezium','Kafka','CDC','Change Data Capture','Apache'] title: 'Streaming Vitess at Bolt'
Previously posted on link at Nov 3, 2020.
Traditionally, MySQL has been used to power most of the backend services at Bolt. We've designed our schemas in a way that they're sharded into different MySQL clusters. Each MySQL cluster contains a subset of data and consists of one primary and multiple replication nodes.
Once data is persisted to the database, we use the Debezium MySQL Connector to capture data change events and send them to Kafka. This gives us an easy and reliable way to communicate changes between back-end microservices.
Vitess at Bolt
Bolt has grown considerably over the past few years, and so did the volume of data written to MySQL. Manual database sharding has become quite an expensive and long-lasting process prone to errors. So we started to evaluate more scalable databases, one of which is Vitess. Vitess is an open-source database clustering system that is based on MySQL and provides horizontal scalability for it. Originated and battle-tested at YouTube, it was later open-sourced and is used by companies like Slack, Github, JD.com to power their backend storage. It combines important MySQL features with the scalability of a NoSQL database.
One of the most important features that Vitess provides is its built-in sharding. It allows the database to grow horizontally by adding new shards in a way that is transparent to back-end application logic. To your application, Vitess appears like a giant single database, but in fact data is partitioned into multiple physical shards behind the scenes. For any table, an arbitrary column can be chosen as the sharding key, and all inserts and updates will be seamlessly directed to a proper shard by Vitess itself.
Figure 1 below illustrates how back-end services interact with Vitess. At a high level, services connect to stateless VTGate instances through a load balancer. Each VTGate has the Vitess cluster's topology cached in its memory and redirects queries to the correct shards and the correct VTTablet (and its underlying MySQL instance) within the shards. More on VTTablet is written below.
Figure 1. Vitess architecture. Reference: https://www.planetscale.com/vitess
Other useful features provided by Vitess are:
- Failover (a.k.a. Reparenting) is easy and transparent for clients. Clients only talk to a VTGate who takes care of failover and service discovery of the new primary transparently.
- It automatically rewrites "problematic" queries that could potentially cause database performance degradation.
- It has a caching mechanism that prevents duplicate queries to reach the underlying MySQL database simultaneously. Only one query will reach the database and its result will be cached and returned to answer duplicate queries.
- It has its connection pool and eliminates the high-memory overhead of MySQL connections. As a result, it can easily handle thousands of connections at the same time.
- Connection timeout and transaction timeout can be configured.
- It has minimal downtime when doing resharding operations.
- Its VStream feature can be used by downstream CDC applications to read change events from Vitess.
Streaming Vitess Options
The ability to capture data changes and publish them to Apache Kafka was one of the requirements for adopting Vitess at Bolt. There were several different options we've considered.
Option 1: Using Debezium MySQL Connector
Applications connect to Vitess VTGate to send queries. VTGate supports the MySQL protocol and has a SQL parser. You can use any MySQL client (e.g. JDBC) to connect to VTGate, which redirects your query to the correct shard and returns the result to your client.
However, VTGate is not equal to a MySQL instance, it is rather a stateless proxy to various MySQL instances. For the MySQL connector to receive change events, the Debezium MySQL connector needs to connect to a real MySQL instance. To make it more obvious, VTGate also has some known compatibility issues, which makes connecting to VTGate different from MySQL.
Another option is to use the Debezium MySQL Connector to connect directly to the underlying MySQL instances of different shards. It has its advantages and disadvantages.
One advantage is that for an unsharded keyspace (Vitess's terminology for a database), the MySQL Connector can continue to work correctly and we don't need to include additional logic or specific implementation. It should just work fine.
One of the biggest disadvantages is that resharding operations would become more complex. For example, the GTID of the original MySQL instance would change when resharded, and the MySQL connector depends on the GTID to work correctly. We also believe that having the MySQL connector connected directly to each underlying MySQL instance defies the purpose of Vitess's operational simplicity as a new connector has to be added (or removed) each time resharding is done. Not to mention that such an operation would lead to data duplication inside Kafka brokers.
Option 2: Using JDBC Source Connector
We've also considered using the JDBC Source Connector. It allows sourcing data from any relational databases that support the JDBC driver into Kafka. Therefore, it is compatible with Vitess VTGate. It has its advantages and disadvantages as well.
Advantages:
- It is compatible with VTGate.
- It handles Vitess resharding operation better. During resharding operation, reads are simply automatically redirected (by VTGate) to the target shards. It won't generate any duplicates or lose any data.
Disadvantages:
- It is poll-based, meaning that the connector polls the database for new change events on a defined interval (typically every few seconds). This means that we would have a much higher latency, compared to the Debezium MySQL Connector.
- Its offsets are managed by either the table's incremental primary key or one of the table's timestamp columns. If we use the timestamp column for offset, we'd have to create a secondary-index of the timestamp column for each table. This adds more constraints on our backend services. If we use the incremental primary key, we would miss the change events for row-updates because the primary key is simply not updated.
- The topic name created by the JDBC connector doesn't include the table's schema name. Using the topic.prefix connector configuration would mean that we'll have one connector per schema. At Bolt, we have a large number of schemas, which means we would need to create a large number of JDBC Source Connectors.
- At Bolt, our downstream applications are already set up to use Debezium's data formats and topic naming conventions, we'd need to change our downstream application's decoding logic to the new data formats.
- Row deletes are not captured.
Option 3: Using VStream gRPC
VTGate exposes a gRPC service called VStream. It is a server-side streaming service. Any gRPC client can subscribe to the VStream service to get a continuous stream of change events from the underlying MySQL instances. The change events that VStream emits have similar information to the MySQL binary logs of the underlying MySQL instances. A single VStream can even subscribe to multiple shards for a given keyspace, making it quite a convenient API to build CDC tools.
Behind the scene, as shown in Figure 2, VStream reads change events from multiple VTTablets - one VTTablet per shard. Therefore, it doesn't send duplicates from multiple VTTablets for a given shard. Each VTTablet is a proxy to its MySQL instance. A typical topology would include one master VTTablet and its corresponding MySQL instance, and multiple replica VTTablets, each of which is the proxy of its own replica MySQL instance. A VTTablet gets change events from its underlying MySQL instance and sends the change events back to VTGate, which in turn sends the change events back to VStream's gRPC client.
When subscribing to the VStream service, the client can specify a VGTID and Tablet Type (e.g. MASTER, REPLICA). The VGTID tells the position from which VStream starts to send change events. Essentially, VGTID includes a list of (keyspace, shard, shard GTID) tuples. The Tablet Type tells which MySQL instance (primary or replica) in each shard do we read change events from.
Figure 2. VStream architecture. Reference: https://vitess.io/docs/concepts/vstream
Some advantages of using VStream gRPC are:
- It is a simple way to receive change events from Vitess. It is also recommended in Vitess's documentation to use VStream to build CDC processes downstream.
- VTGate hides the complexity of connecting to various source MySQL instances.
- It has low latency since change events are streamed to the client as soon as they happen.
- The change events include not only inserts and updates, but also deletes.
- Probably one of the biggest advantages is that the change events contain the schema of each table. So you don't have to worry about fetching each table's schema in advance (by, for example, parsing DDLs or querying the table's definition).
- The change events have VGTID included, which the CDC process can store and use as the offset from where to restart the CDC process next time.
- Also importantly, VStream is designed to work well with Vitess operations such as Resharding and Moving Tables.
There are also some disadvantages:
- Although it includes table schemas, some important information is still missing. For example, the Enum and Set column types don't provide all the allowed values yet. This should be fixed in the next major release (Vitess 9) though.
- Since VStream is a gRPC service, we cannot use the Debezium MySQL Connector out-of-the-box. However, it is quite straightforward to implement the gRPC client in other languages.
All things considered, we've decided to use VStream gRPC to capture change events from Vitess and implement our Vitess Connector based on all the best practices of Debezium.
Vitess Connector Deep Dive and Open Source
After we've decided to implement our Vitess Connector, we started looking into the implementation details of various Debezium source connectors (MySQL, Postgres, SQLServer), to borrow some ideas. Almost all of them are implemented using a common Connector development framework. So it was clear we should develop the Vitess connector on top of it. We are very active users of the MySql Connector and we benefit from it being open-sourced, as it allows us to contribute to it things we were missing ourselves. So we decided we want to give back to the community and open-source the Vitess source connector code-base under the Debezium umbrella. Please feel free to learn more at Debezium Connector Vitess. We welcome and value any contributions.
At a high level, as you can see below, connector instances are created in Kafka Connect workers. At the time of writing, you have two options to configure the connector to read from Vitess:
Option 1 (recommended):
As shown in Figure 3, each connector captures change events from all shards in a specific keyspace. If the keyspace is not sharded, the connector can still capture change events from the only shard in the keyspace. When it's the first time that the connector starts, it reads from the current VGTID position of all shards in the keyspace. Because it subscribes to all shards, it continuously captures change events from all shards and sends them to Kafka. It automatically supports the Vitess Reshard operation, there is no data loss, nor duplication.
Figure 3. Each connector subscribes to all shards of a specific keyspace
Option 2:
As shown in Figure 4, each connector instance captures change events from a specific keyspace/shard pair. The connector instance gets the initial (the current) VGTID position of the keyspace/shard pair from VTCtld gRPC, which is another Vitess component. Each connector instance, independently, uses the VGTID it gets to subscribe to VStream gRPC and continuously capture change events from VStream and sends them to Kafka. To support the Vitess Reshard operation, you would need more manual operations.
Figure 4. Each connector subscribes to one shard of a specific keyspace
Internally, each connector task uses a gRPC thread to constantly receive change events from VStream and puts the events into an internal blocking queue. The connector task thread polls events out of the queue and sends them to Kafka, as can be seen in Figure 5.
Figure 5. How each connector task works internally
Replication Challenges
While we were implementing the Vitess Connector and digging deeper into Vitess, we've also realized a few challenges.
Vitess Reshard
The Vitess connector supports the Vitess Reshard operation when the connector is configured to subscribe to all shards of a given keyspace. VStream sends a VGTID that contains the shard GTID for all shards. Vitess Resharding is transparent to users. Once it's completed, Vitess will send the VGTID of the new shards. Therefore, the connector will use the new VGTID after reshard. However, you need to make sure that the connector is up and running when the reshard operation takes place. Especially please check that the offset topic of the connector has the new VGTID before deleting the old shards. This is because in case the old shards are deleted, VStream will not be able to recognize the VGTID from the old shards.
If you decide to subscribe to one shard per connector, the connector does not provide out-of-the-box support for Vitess resharding. One manual workaround to support resharding is creating one new connector per target shard. For example, one new connector for the commerce/-80 shard, and another new connector for the commerce/80- shard. Bear in mind that because they're new connectors, by default, new topics will be created, however, you could use the Debezium logical topic router to route the records to the same kafka topics.
Offset Management
VStream includes a VGTID event in its response. We save the VGTID as the offset in the Kafka offset topic, so when the connector restarts, we can start from the saved VGTID. However, in rare cases when a transaction includes a huge amount of rows, VStream batches the change events into multiple responses, and only the last response has the VGTID. In such cases, we don't have the VGTID for every change event we receive. We have a few options to solve this particular issue:
- We can buffer all the change events in memory and wait for the last response that contains the VGTID to arrive. So all events will have the correct VGTID associated with them. A few disadvantages are that we'll have higher latency before events are sent to Kafka. Also, memory usage could potentially increase quite a lot due to buffering. Buffering also adds complexity to the logic. We also have no control over the number of events VStream sends to us.
- We can use the latest VGTID we have, which is the VGTID from the previous VStream response. If the connector fails and restarts when processing such a big transaction, it'll restart from the VGTID of the previous VStream response, thus reprocessing some events. Therefore, it has at-least-once event delivery semantics and it expects the downstream to be idempotent. Since most transactions are not big enough, most VStream responses will have VGTID in the response, so the chance of having duplicates is low. In the end, we chose this approach for its at-least-once delivery guarantee and its design simplicity.
Schema Management
VStream's response also includes a FIELD event. It's a special event that contains the schemas of the tables of which the rows are affected. For example, let's assume we have 2 tables, A and B. If we insert a few rows into table A, the FIELD event will only contain table A's schema. The VStream is smart enough to only include the FIELD event whenever necessary. For example, when a VStream client reconnects, or when a table's schema is changed.
The older version of VStream includes only the column type (e.p. Integer, Varchar), no additional information such as whether the column is the primary key, whether the column has a default value, Decimal type's scale and precision, Enum type's allowed values, etc.
The newer version (Vitess 8) of VStream starts to include more information on each column. This will help the connector to deserialize more accurately certain types and have a more precise schema in the change events sent to Kafka.
Future Development Work
- We can use VStream's API to start streaming from the latest VGTID position, instead of getting the initial VGTID position from VTCtld gRPC. Doing so would eliminate the dependency from VTCtld.
- We don't support automatically extracting the primary keys from the change events yet. Currently, by default, all change events sent to Kafka have null as the key, unless the message.key.columns connector configuration is specified. Vitess recently added flags of each column in the VStream FIELD event, which allows us to implement this feature soon.
- Add support for initial snapshots to capture all existing data before streaming changes.
Summary
MySQL has been used to power most of our backend services at Bolt. Due to the considerable growth of the volume of data and operational complexity, Bolt started to evaluate Vitess for its scalability and its built-in features such as resharding.
To capture data changes from Vitess, as what we've been doing with Debezium MySQL Connector, we've considered a few options. In the end, we have implemented our own Vitess Connector based on the common Debezium connector framework. While implementing the Vitess connector, we've encountered a few challenges. For example, support for the Vitess reshard operation, offset management, and schema management. We reasoned about ways to address the challenges and what we worked out as solutions.
We've also received quite some interest from multiple communities in this project and we've decided to open-source Vitess Connector under the Debezium umbrella. Please feel free to learn more, and we welcome and value any contributions.
File: content/en/blog/2020-11-09-vitess-operator-for-kubernetes.md
author: 'Alkin Tezuysal'
date: 2020-11-09
slug: '2020-11-09-vitess-operator-for-kubernetes'
tags: ['Vitess','MySQL','kubernetes','operator','cloud','GKE','sharding']
title: 'Vitess Operator for Kubernetes'
Introduction
In this blog, I would like to explore Vitess Operator for Kubernetes. This post demonstrates the sample implementation of Vitess in Kubernetes topology. I also explore common DBA tasks by demonstrating how they are handled in the Vitess ecosystem. Vitess, out of the box, comes with a lot of tools and utilities that one has to either incorporate or develop to manage MySQL topology. Letβs take a look at the capabilities of Vitess in these areas and demonstrate how they are performed under the operator realm.
Prerequisites
- GKE Account
- Kubectl
- MySQL Client
- Install vtctlclient locally
- go get vitess.io/vitess/go/cmd/vtctlclient
- Download the Operator example files
- git clone [email protected]:vitessio/vitess.git
- cd vitess/examples/operator
- Run sample database implementation (Optional).
Install the Vitess Operator
$ gcloud container clusters create vitess-k8s-operator --cluster-version 1.14 --zone us-east1-b --enable-autoscaling --min-nodes 8 --max-nodes 12
Creating cluster vitess-k8s-operator in us-east1-b... Cluster is being health-checked (master is healthy)...done.
Created [https://container.googleapis.com/v1/projects/planetscale-dev/zones/us-east1-b/clusters/vitess-k8s-operator].
To inspect the contents of your cluster, go to:
https://console.cloud.google.com/kubernetes/workload_/gcloud/us-east1-b/vitess-k8s-operator?project=planetscale-dev
kubeconfig entry generated for vitess-k8s-operator.NAME LOCATION MASTER_VERSION MASTER_IP MACHINE_TYPE NODE_VERSION NUM_NODES STATUS
vitess-k8s-operator us-east1-b 1.14.10-gke.50 35.237.26.125 n1-standard-1 1.14.10-gke.50 3 RUNNING
$ cd vitess/examples/operator
$ kubectl apply -f operator.yaml
customresourcedefinition.apiextensions.k8s.io/etcdlockservers.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitessbackups.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitessbackupstorages.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitesscells.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitessclusters.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitesskeyspaces.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitessshards.planetscale.com created
serviceaccount/vitess-operator created
role.rbac.authorization.k8s.io/vitess-operator created
rolebinding.rbac.authorization.k8s.io/vitess-operator created
priorityclass.scheduling.k8s.io/vitess created
priorityclass.scheduling.k8s.io/vitess-operator-control-plane created
deployment.apps/vitess-operator created
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
vitess-operator-8454d86687-hv9lg 1/1 Running 0 41sBring up an initial test cluster
$ kubectl apply -f 101_initial_cluster.yaml
vitesscluster.planetscale.com/example created
secret/example-cluster-config created
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
example-etcd-faf13de3-1 1/1 Running 0 54s
example-etcd-faf13de3-2 1/1 Running 0 54s
example-etcd-faf13de3-3 1/1 Running 0 53s
example-vttablet-zone1-2469782763-bfadd780 3/3 Running 1 54s
example-vttablet-zone1-2548885007-46a852d0 2/3 Running 1 54s
example-zone1-vtctld-1d4dcad0-59d8498459-54p68 1/1 Running 1 54s
example-zone1-vtgate-bc6cde92-6fcfbb6666-5bcjc 1/1 Running 1 53s
vitess-operator-8454d86687-hv9lg 1/1 Running 0 2m28sSetup Port-forward
$ ./pf.sh &
[1] 34424
askdba:operator askdba$ You may point your browser to http://localhost:15000, use the following aliases as shortcuts:
alias vtctlclient="vtctlclient -server=localhost:15999 -logtostderr"
alias mysql="mysql -h 127.0.0.1 -P 15306 -u user"
Hit Ctrl-C to stop the port forwards
Forwarding from 127.0.0.1:15306 -> 3306
Forwarding from [::1]:15306 -> 3306
Forwarding from 127.0.0.1:15000 -> 15000
Forwarding from [::1]:15000 -> 15000
Forwarding from 127.0.0.1:15999 -> 15999
Forwarding from [::1]:15999 -> 15999$ vtctlclient ApplySchema -sql="$(cat create_commerce_schema.sql)" commerce
$ vtctlclient ApplyVSchema -vschema="$(cat vschema_commerce_initial.json)" commerce
Handling connection for 15999
New VSchema object:
{
"tables": {
"corder": {
},
"customer": {
},
"product": {
}
}
}
If this is not what you expected, check the input data (as JSON parsing will skip unexpected fields).After this section itβs recommended to to continue with the sample database steps to have a running database in this cluster(optional).
Database Operations
In this section as weβve mentioned above, Iβd like to show how to perform functional operations as follows:
- Backup & Recovery
- Failover to Replica
- Schema Change
Backup Vitess Tablet
At this stage, our cluster within Kubernetes is up, but backups wonβt work until we configure a place to store them.
First, we will check existing backups and as you can see there are none.
No resources found in default namespace.In order to perform backups, we need to set up a backup storage bucket in GCS.
Fill in your own values for all the my-* names. The bucket name in particular must be globally unique across all GCS users.
Select GCP project
$ gcloud config set project [project-name]
Updated property [core/project].Create a GCS bucket
$ gsutil mb -l us-central1 -b on gs://my-vitess-operator-backup-bucket
Creating gs://my-vitess-operator-backup-bucket/...Create a GCP service account
$ gcloud iam service-accounts create my-backup-service-account
Created service account [my-backup-service-account].Grant the service account access to the bucket gsutil iam ch
$ gsutil iam ch serviceAccount:my-backup-service-account@planetscale-dev.iam.gserviceaccount.com:objectViewer,objectCreator,objectAdmin \
gs://my-vitess-operator-backup-bucketCreate and download a key for the service account
$ gcloud iam service-accounts keys create ~/gcs_key.json --iam-account my-backup-service-account@planetscale-dev.iam.gserviceaccount.com
created key [ccd65b5a198298f9ca07ee6ab901a2492ea142c7] of type [json] as [/Users/askdba/gcs_key.json]
for [my-backup-service-account@planetscale-dev.iam.gserviceaccount.com]Upload the service account key as a k8s Secret
$ kubectl create secret generic gcs-auth --from-file=gcs_key.json="$HOME/gcs_key.json"
secret/gcs-auth createdDelete the local copy
$ rm ~/gcs_key.jsonCheck Tablet(s) status
$ kubectl describe vt | grep 'Tablets'
Desired Tablets: 2
Ready Tablets: 2
Tablets: 2
Updated Tablets: 2
Desired Tablets: 6
Ready Tablets: 6
Tablets: 6
Updated Tablets: 6Note: The numbers will be different if you ran the optional sample database steps.
At this stage, our cluster still has no association with the GSC bucket. We need to apply the correct backup method (xtrabackup) and bucket definition to the cluster via YAML file.
Add a backup section under spec in each VitessCluster YAML before applying it. Since this is an idempotent operation we can edit and re-apply 101_initial_cluster.yaml file.
yaml
spec:
backup:
engine: xtrabackup
locations:
- gcs:
bucket: my-vitess-backup-bucket
authSecret:
name: gcs-auth
key: gcs_key.json$ kubectl apply -f 101_initial_cluster.yaml
vitesscluster.planetscale.com/example configured
secret/example-cluster-config configured
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
example-90089e05-vitessbackupstorage-subcontroller 1/1 Running 0 29s
example-commerce-x-x-vtbackup-init-c6db73c9 0/1 CrashLoopBackOff 1 29s
example-etcd-faf13de3-1 1/1 Running 0 7m51s
example-etcd-faf13de3-2 1/1 Running 0 7m51s
example-etcd-faf13de3-3 1/1 Running 0 7m51s
example-vttablet-zone1-2469782763-bfadd780 3/3 Running 0 15s
example-vttablet-zone1-2548885007-46a852d0 3/3 Running 2 7m51s
example-zone1-vtctld-1d4dcad0-59d8498459-qg4rv 1/1 Running 3 7m51s
example-zone1-vtgate-bc6cde92-6fcfbb6666-gz6mm 1/1 Running 3 7m50s
vitess-operator-8454d86687-m225m 1/1 Running 0 8m5sIf we had configured backups in the VitessCluster before the initial deployment, the operator would initialize backup storage automatically. Since we initially started the cluster without backups configured, the automatic backup initialization will fail:
$ kubectl logs example-commerce-x-x-vtbackup-init-c6db73c9
ERROR: logging before flag.Parse: E0928 12:08:20.897936 1 syslogger.go:122] can't connect to syslog
E0928 12:08:21.075860 1 vtbackup.go:177] Can't take backup: refusing to upload initial backup of empty database: the shard commerce/-
already has at least one tablet that may be serving (zone1-2469782763); you must take a backup from a live tablet insteadThis means we need to take a backup manually to initialize backup storage:
$ vtctlclient -logtostderr BackupShard commerce/-
β¦
I0928 15:13:29.818114 80158 main.go:64] I0928 12:13:29.492382 backup.go:162] I0928 12:13:29.492048 xtrabackupengine.go:309] xtrabackup stderr: 200928 12:13:29 [00] Streaming <STDOUT>
I0928 15:13:29.818123 80158 main.go:64] I0928 12:13:29.492404 backup.go:162] I0928 12:13:29.492133 xtrabackupengine.go:309] xtrabackup stderr: 200928 12:13:29 [00] ...done
I0928 15:13:29.818131 80158 main.go:64] I0928 12:13:29.492415 backup.go:162] I0928 12:13:29.492217 xtrabackupengine.go:309] xtrabackup stderr: xtrabackup: Transaction log of lsn (2747504) to (2747513) was copied.
I0928 15:13:29.818145 80158 main.go:64] I0928 12:13:29.594417 backup.go:162] I0928 12:13:29.593983 xtrabackupengine.go:309] xtrabackup stderr: 200928 12:13:29 completed OK!
I0928 15:13:29.818160 80158 main.go:64] I0928 12:13:29.622037 backup.go:162] I0928 12:13:29.615593 xtrabackupengine.go:631] Found position: 3d370970-0182-11eb-9c3b-767b9aee7c34:1-9,3d3e599f-0182-11eb-88a6-a69501e63cc3:1-3
I0928 15:13:29.818168 80158 main.go:64] I0928 12:13:29.622109 backup.go:162] I0928 12:13:29.615717 xtrabackupengine.go:115] Closing backup file backup.xbstream.gz-000
I0928 15:13:30.160490 80158 main.go:64] I0928 12:13:29.999008 backup.go:162] I0928 12:13:29.996710 xtrabackupengine.go:115] Closing backup file backup.xbstream.gz-001
I0928 15:13:30.321497 80158 main.go:64] I0928 12:13:30.160952 backup.go:162] I0928 12:13:30.160183 xtrabackupengine.go:115] Closing backup file backup.xbstream.gz-002
I0928 15:13:30.493284 80158 main.go:64] I0928 12:13:30.333110 backup.go:162] I0928 12:13:30.332349 xtrabackupengine.go:115] Closing backup file backup.xbstream.gz-003
I0928 15:13:30.594650 80158 main.go:64] I0928 12:13:30.433818 backup.go:162] I0928 12:13:30.433292 xtrabackupengine.go:115] Closing backup file backup.xbstream.gz-004
I0928 15:13:30.752338 80158 main.go:64] I0928 12:13:30.591845 backup.go:162] I0928 12:13:30.590837 xtrabackupengine.go:115] Closing backup file backup.xbstream.gz-005
I0928 15:13:30.862331 80158 main.go:64] I0928 12:13:30.702971 backup.go:162] I0928 12:13:30.702169 xtrabackupengine.go:115] Closing backup file backup.xbstream.gz-006
I0928 15:13:31.027650 80158 main.go:64] I0928 12:13:30.868250 backup.go:162] I0928 12:13:30.867350 xtrabackupengine.go:115] Closing backup file backup.xbstream.gz-007
I0928 15:13:31.209019 80158 main.go:64] I0928 12:13:31.049203 backup.go:162] I0928 12:13:31.047831 xtrabackupengine.go:162] Writing backup MANIFEST
I0928 15:13:31.209046 80158 main.go:64] I0928 12:13:31.049501 backup.go:162] I0928 12:13:31.048074 xtrabackupengine.go:196] Backup completed
I0928 15:13:31.209057 80158 main.go:64] I0928 12:13:31.049599 backup.go:162] I0928 12:13:31.048087 xtrabackupengine.go:115] Closing backup file MANIFESTWithin a minute or so, we should see the new backup appear when listing VitessBackup CRDs:
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
example-90089e05-vitessbackupstorage-subcontroller 1/1 Running 0 6m41s
example-etcd-faf13de3-1 1/1 Running 0 14m
example-etcd-faf13de3-2 1/1 Running 0 14m
example-etcd-faf13de3-3 1/1 Running 0 14m
example-vttablet-zone1-2469782763-bfadd780 3/3 Running 0 6m27s
example-vttablet-zone1-2548885007-46a852d0 3/3 Running 0 5m33s
example-zone1-vtctld-1d4dcad0-59d8498459-qg4rv 1/1 Running 3 14m
example-zone1-vtgate-bc6cde92-6fcfbb6666-gz6mm 1/1 Running 3 14m
vitess-operator-8454d86687-m225m 1/1 Running 0 14m
$ kubectl get vitessbackups
NAME AGE
example-commerce-x-x-20200928-121327-97ece60f-b8bc0ec7 2m18sRestore Vitess Tablet
Under normal circumstances, you shouldnβt ever have to restore a backup manually. Extending the number of tablets in a cluster will make the new vttablets automatically restore from the latest backup, then point themselves at the current master. Once caught up, theyβll go into serving state. Hereβs how to do it manually for demonstration purposes.
$ vtctlclient ListAllTablets
Handling connection for 15999
zone1-2469782763 commerce - master 10.100.1.37:15000 10.100.1.37:3306 []
zone1-2548885007 commerce - replica 10.100.4.17:15000 10.100.4.17:3306 []
$ vtctlclient -logtostderr RestoreFromBackup zone1-2548885007
I0928 15:28:04.783441 80378 main.go:64] I0928 12:28:04.172914 backup.go:247] I0928 12:28:04.172087 xtrabackupengine.go:398]
Restore: returning replication position 3d370970-0182-11eb-9c3b-767b9aee7c34:1-9,3d3e599f-0182-11eb-88a6-a69501e63cc3:1-3
I0928 15:28:04.783449 80378 main.go:64] I0928 12:28:04.173170 backup.go:247] I0928 12:28:04.172126 backup.go:308] Restore: starting mysqld for mysql_upgrade
I0928 15:28:07.271912 80378 main.go:64] I0928 12:28:07.177696 backup.go:247] I0928 12:28:07.176828 backup.go:315] Restore: running mysql_upgrade
I0928 15:28:08.752154 80378 main.go:64] I0928 12:28:08.657377 backup.go:247] I0928 12:28:08.656674 backup.go:326] Restore: populating local_metadata
I0928 15:28:08.777876 80378 main.go:64] I0928 12:28:08.683299 backup.go:247] I0928 12:28:08.682656 backup.go:334] Restore: restarting mysqld after mysql_upgradeList cells/keyspaces/shards/tablets
$ kubectl describe vtc
Name: example-zone1-5abb61ae
Namespace: default
Labels: planetscale.com/cell=zone1
planetscale.com/cluster=example
Annotations: <none>
API Version: planetscale.com/v2
Kind: VitessCell
Metadata:
Creation Timestamp: 2020-09-28T12:00:26Z
Generation: 1
Owner References:
API Version: planetscale.com/v2
Block Owner Deletion: true
Controller: true
Kind: VitessCluster
Name: example
UID: 323a1cfa-0182-11eb-9bbc-42010a8e01fe
Resource Version: 2105764
$ kubectl get vtk
NAME AGE
example-commerce-fb9b866a 30mList tablets for a particular keyspace/shard
$ kubectl get pods -l planetscale.com/component=vttablet,planetscale.com/keyspace=commerce,planetscale.com/shard=x-x
NAME READY STATUS RESTARTS AGE
example-vttablet-zone1-2469782763-bfadd780 3/3 Running 0 24m
example-vttablet-zone1-2548885007-46a852d0 3/3 Running 0 23mFailover Scenario
In this section, letβs say we think our primary is not in good shape and weβd like to force a failover to the replica. We could use the drain feature of the operator to request a graceful failover to a replica. The operator will choose another suitable replica if one is available, healthy, and not itself drained.
First check who is the current master of a given shard.
$ kubectl describe vts example-commerce-x-x-0f5afee6 | grep 'Master Alias'
Master Alias: zone1-2469782763List tablets for that shard:
$ kubectl get pods -l planetscale.com/component=vttablet,planetscale.com/keyspace=commerce,planetscale.com/shard=x-x
NAME READY STATUS RESTARTS AGE
example-vttablet-zone1-2469782763-bfadd780 3/3 Running 0 28m
example-vttablet-zone1-2548885007-46a852d0 3/3 Running 0 27m
$ vtctlclient ListAllTablets
Handling connection for 15999
zone1-2469782763 commerce - master 10.100.1.37:15000 10.100.1.37:3306 []
zone1-2548885007 commerce - replica 10.100.4.17:15000 10.100.4.17:3306 []Drain mastership to some other tablet (e.g. to prepare to drain the Node itβs on) by annotating the current master tablet.
$ kubectl annotate pod example-vttablet-zone1-2469782763-bfadd780 drain.planetscale.com/started="Draining for blog"
pod/example-vttablet-zone1-2469782763-bfadd780 annotatedCheck failover status to see that a new master has been elected:
$ kubectl describe vts example-commerce-x-x-0f5afee6 | grep 'Master Alias'
Master Alias: zone1-2548885007To avoid leaving any tablets in a drained state, we can undrain all of them by removing the annotation:
$ kubectl annotate pod -l planetscale.com/component=vttablet drain.planetscale.com/started-
pod/example-vttablet-zone1-2469782763-bfadd780 annotated
pod/example-vttablet-zone1-2548885007-46a852d0 annotatedAt the time of writing this blog post thereβs a huge amount of work by PlanetScaleβs Vitess team to integrate failovers with the Orchestrator project. You can see a demo by Sugu here.
Schema Changes
In this section, Iβd like to demonstrate how to apply schema changes to the Vitess cluster. For this operation itβs possible to use the following methods:
- ApplySchema - Weβve seen examples of ApplySchema during initialization steps of the cluster.
- VTGate - This is a method to send direct DDL statements to the Vitess cluster.
- Directly to MySQL using Online Schema Change tools such as pt-online-schema and gh-ost.
- New and Experimental in Vitess 8.0: managed Online DDL. Users will use a special ALTER TABLE syntax, either via ApplySchema or via VTGate, and Vitess will automate an online schema change via gh-ost or pt-online-schema-change on relevant shards, giving the user visibility and control over the migration. The user will not need to know how to run gh-ost or online-schema-change. Vitess will take care of setup, discovery, throttling, and finally, cleanup.
We find that there is no common practice to automating schema changes in production on large, sharded databases. Some companies develop their own automation flow. In many others that weβve observed, schema changes are applied manually by database engineers. These engineers will have resolved which clusters are to be affected, which shards are in those clusters, which servers are in those shards, and what migration commands to run. The engineers will run gh-ost or online-schema-change manually, check for errors, and handle cleanup of tables and triggers etc. This is why we have created the Online DDL flow in Vitess 8.0.
This new functionality is still Experimental, and we will discuss it another time. Meanwhile, letβs describe how an engineer would manage online schema changes directly, by running pt-online-schema-change manually on relevant shards. Our friends at Percona were kind enough to build a Docker Image with Percona Toolkit and MySQL Client. Hereβs where you can find this image that weβre going to use as a sidecar to our operator implementation. This will give us a clean cluster with a sidecar built in.
Note: This will remove customized backup configurations in prior sections.
$ kubectl apply -f 101_initial_cluster.yaml.sidecar
vitesscluster.planetscale.com/example configured
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
example-etcd-faf13de3-1 1/1 Running 0 119m
example-etcd-faf13de3-2 1/1 Running 0 119m
example-etcd-faf13de3-3 1/1 Running 0 119m
example-vttablet-zone1-2469782763-bfadd780 4/4 Running 1 119m
example-vttablet-zone1-2548885007-46a852d0 4/4 Running 1 119m
example-zone1-vtctld-1d4dcad0-59d8498459-ksvqp 1/1 Running 2 119m
example-zone1-vtgate-bc6cde92-6fcfbb6666-2j9cz 1/1 Running 2 119m
vitess-operator-8454d86687-hj77s 1/1 Running 0 3d5h
$ kubectl describe pods example-vttablet-zone1-2548885007-46a852d0 | grep percona
image: perconalab/percona-toolkit
name: percona-toolkitOur default example consists of commerce database with three tables as seen below:
mysql> use commerce
Database changed
mysql> show tables;
+-----------------------+
| Tables_in_vt_commerce |
+-----------------------+
| corder |
| customer |
| product |
+-----------------------+
3 rows in set (0.15 sec)Letβs say we need to alter corder table and modify order_id column. Weβll assume this table is big so we would like to make this schema migration online with minimum impact to production workloads.
$ vtctlclient ListAllTablets
Handling connection for 15999
zone1-2469782763 commerce - master 10.100.4.34:15000 10.100.4.34:3306 []
zone1-2548885007 commerce - replica 10.100.5.32:15000 10.100.5.32:3306 []
$ kubectl exec --stdin --tty -c percona-toolkit example-vttablet-zone1-2469782763-bfadd780 -- bashbash-4.4$ pt-online-schema-change --socket /vt/socket/mysql.sock \
--user=vt_dba h=localhost,D=vt_commerce,t=corder \
--critical-load threads_running=10000000000 \
--max-load threads_running:20 \
--tries create_triggers:10000:1,drop_triggers:10000:1,swap_tables:10000:1,update_foreign_keys:10000:1,copy_rows:10000:1 \
--set-vars lock_wait_timeout=5 \
--pause-file=/tmp/pause-osc \
--alter="MODIFY order_id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT" \
--recursion-method=none --execute
No slaves found. See --recursion-method if host example-vttablet-zone1-2469782763-bfadd780 has slaves.
Not checking slave lag because no slaves were found and --check-slave-lag was not specified.
Operation, tries, wait:
analyze_table, 10, 1
copy_rows, 10000, 1
create_triggers, 10000, 1
drop_triggers, 10000, 1
swap_tables, 10000, 1
update_foreign_keys, 10000, 1
Altering `vt_commerce`.`corder`...
Creating new table...
Created new table vt_commerce._corder_new OK.
Altering new table...
Altered `vt_commerce`.`_corder_new` OK.
2020-10-12T12:09:05 Creating triggers...
2020-10-12T12:09:05 Created triggers OK.
2020-10-12T12:09:05 Copying approximately 1 rows...
2020-10-12T12:09:05 Copied rows OK.
2020-10-12T12:09:05 Analyzing new table...
2020-10-12T12:09:05 Swapping tables...
2020-10-12T12:09:05 Swapped original and new tables OK.
2020-10-12T12:09:05 Dropping old table...
2020-10-12T12:09:05 Dropped old table `vt_commerce`.`_corder_old` OK.
2020-10-12T12:09:05 Dropping triggers...
2020-10-12T12:09:05 Dropped triggers OK.
Successfully altered `vt_commerce`.`corder`.
$mysql -S /vt/socket/mysql.sock -u vt_dba
mysql> show create table corder;
+--------+-----------------------------------------------------------------------------+
| Table | Create Table |
+--------+-----------------------------------------------------------------------------+
| corder | CREATE TABLE `corder` (
`order_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`customer_id` bigint(20) DEFAULT NULL,
`sku` varbinary(128) DEFAULT NULL,
`price` bigint(20) DEFAULT NULL,
PRIMARY KEY (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+--------+-----------------------------------------------------------------------------+
1 row in set (0.00 sec)Letβs say we have followed the instructions and built a sharded cluster in such a state.
$ echo "show vitess_tablets;" | mysql --table
Handling connection for 15306
+-------+----------+-------+------------+-------------+------------------+-------------+
| Cell | Keyspace | Shard | TabletType | State | Alias | Hostname |
+-------+----------+-------+------------+-------------+------------------+-------------+
| zone1 | commerce | - | MASTER | SERVING | zone1-2469782763 | 10.100.6.13 |
| zone1 | commerce | - | REPLICA | SERVING | zone1-2548885007 | 10.100.5.37 |
| zone1 | customer | - | MASTER | NOT_SERVING | zone1-1250593518 | 10.100.5.36 |
| zone1 | customer | - | REPLICA | SERVING | zone1-3778123133 | 10.100.4.38 |
| zone1 | customer | -80 | MASTER | SERVING | zone1-0120139806 | 10.100.1.59 |
| zone1 | customer | -80 | REPLICA | SERVING | zone1-2289928654 | 10.100.2.25 |
| zone1 | customer | 80- | MASTER | SERVING | zone1-0118374573 | 10.100.0.25 |
| zone1 | customer | 80- | REPLICA | SERVING | zone1-4277914223 | 10.100.3.45 |
+-------+----------+-------+------------+-------------+------------------+-------------+We would have to do the same for each shardβs MASTER.
As you can see above the same approach can be followed with other tools such as gh-ost, proxysql etc. Sidecar approach is gaining popularity to tackle some of the operational database problems recently.
Conclusion
In conclusion, Vitess Operator is a very powerful option when it comes to deploying your database cluster in Kubernetes. By testing possibilities and initial challenges I hope you found this demonstration useful. Kubernetes Operators are growing rapidly and empower the worldβs best cloud services.
Credits & References
- Percona Engineering and Release team
- PlanetScale Vitess Engineering team
File: content/en/blog/2020-11-30-how-to-deploy-django.md
author: 'Alkin Tezuysal'
date: 2020-11-30
slug: '2020-11-30-how-to-deploy-django'
tags: ['Vitess','MySQL','kubernetes','operator','cloud','GKE','sharding']
title: 'Django with Vitess'
Django is a popular framework for Python application developers. It includes packages which make tasks like authorization and content administration easier. Django supports a number of databases including MySQL which makes it possible to run a Django application over Vitess without having to change the application code. Letβs take a look at how to combine the strengths of these two open source frameworks.
We built this example using Vitess operator. You can see the details of the implementation in the blog post Vitess Operator for Kubernetes.
Prerequisites
- Python environment locally (3.X)
- Kubernetes access (minikube, GKE)
- Support for Django ORM via Vitess
For this example, weβre using GKE with an existing Kubernetes cluster. You can also do this via minikube locally.
The Django example we are using is the "weather app". We first launch the vitess operator using the provided configuration.
The following section includes these steps:
- Creating a Vitess Operator pod
- Building Vitess Cluster Components (1x primary tablet, 1x replica tablet, 3x etcd pods, 1x vtgate, 1x vtctld, 1x vitessbackup)
- Create the βweatherappβ database schema and users.
$ kubectl apply -f operator.yaml
customresourcedefinition.apiextensions.k8s.io/etcdlockservers.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitessbackups.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitessbackupstorages.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitesscells.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitessclusters.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitesskeyspaces.planetscale.com created
customresourcedefinition.apiextensions.k8s.io/vitessshards.planetscale.com created
serviceaccount/vitess-operator created
role.rbac.authorization.k8s.io/vitess-operator created
rolebinding.rbac.authorization.k8s.io/vitess-operator created
priorityclass.scheduling.k8s.io/vitess created
priorityclass.scheduling.k8s.io/vitess-operator-control-plane created
deployment.apps/vitess-operator created
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
vitess-operator-7f9c9d58f6-q5zlf 1/1 Running 0 20sInitialize this cluster with a sample database called βweatherappβ and user/password to access it will be embedded in the configuration file. We are basically creating a database which is analogous to a keyspace in Vitess.
$ kubectl apply -f 101_initial_cluster.yaml.django
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
example-90089e05-vitessbackupstorage-subcontroller 1/1 Running 0 94s
example-etcd-faf13de3-1 1/1 Running 0 94s
example-etcd-faf13de3-2 1/1 Running 0 94s
example-etcd-faf13de3-3 1/1 Running 0 94s
example-vttablet-zone1-1542279354-edf1c7bf 2/3 Running 1 94s
example-vttablet-zone1-3763665199-476cbd65 2/3 Running 2 94s
example-weatherapp-x-x-vtbackup-init-75efaeeb 0/1 Completed 0 74s
example-zone1-vtctld-1d4dcad0-67bfd56b8b-4dr9s 1/1 Running 2 94s
example-zone1-vtgate-bc6cde92-59b88bc8d8-6wz86 1/1 Running 2 94s
vitess-operator-7f9c9d58f6-q5zlf 1/1 Running 0 4m30sAs you can see this brings up a fully functional managed Vitess cluster with an unsharded keyspace consisting of one βPrimary (Master)β and one βReplicaβ.
Step 1 - Set portforwards:
$ cat pf.sh ; ./pf.sh &
#!/bin/sh
kubectl port-forward --address localhost "$(kubectl get service --selector="planetscale.com/component=vtctld" -o name | head -n1)" 15000 15999 &
process_id1=$!
kubectl port-forward --address localhost "$(kubectl get service --selector="planetscale.com/component=vtgate,!planetscale.com/cell" -o name | head -n1)" 15306:3306 &
process_id2=$!
sleep 2
echo "You may point your browser to http://localhost:15000, use the following aliases as shortcuts:"
echo 'alias vtctlclient="vtctlclient -server=localhost:15999 -logtostderr"'
echo 'alias mysql="mysql -h 127.0.0.1 -P 15306 -u user"'
echo "Hit Ctrl-C to stop the port forwards"
wait $process_id1
wait $process_id2Check Tablets:
$ vtctlclient ListAllTablets
Handling connection for 15999
zone1-1542279354 weatherapp - replica 10.100.1.75:15000 10.100.1.75:3306 [] <null>
zone1-3763665199 weatherapp - master 10.100.3.57:15000 10.100.3.57:3306 [] 2020-10-16T09:06:59ZStep 2 - Verify database:
$ alias mysql="mysql -h 127.0.0.1 -P 15306 -u djangouser -p"
$ mysql
mysql: [Warning] Using a password on the command line interface can be insecure.
Handling connection for 15306
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.7.9-Vitess MySQL Community Server (GPL)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+------------+
| Databases |
+------------+
| weatherapp |
+------------+
1 row in set (0.16 sec)Step 3 - Setup application environment
Now that we have set up the Vitess cluster with a MySQL backend, we can proceed to building the Django application. We will build a Django project using the django-admin command.
$ mkdir my_weather_app
$ cd my_weather_app
$ python3 -m venv env
$ . env/bin/activate
(env) askdba:my_weather_app askdba$
$ pip install django
$ django-admin startproject weatherapp
$ cd weatherapp/
$ ls -la
total 8
drwxr-xr-x 4 askdba staff 128 Oct 16 12:19 .
drwxr-xr-x 4 askdba staff 128 Oct 16 12:18 ..
-rwxr-xr-x 1 askdba staff 666 Oct 16 12:18 manage.py
drwxr-xr-x 7 askdba staff 224 Oct 16 12:18 weatherapp
Edit configuration file and update following section.
$ vi weatherapp/settings.py [link to sample file]
import os
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'custom_db_backends.vitess',
'OPTIONS': {
'read_default_file': '/usr/local/mysql/my.cnf',
},
}
}
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
...
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1']
# Application definition
...Copy customs_db_backends directory to your project directory. You can clone Vitess project to a local directory.
$ cp -r ~/vitess/support/django/custom_db_backends .
$ vi /usr/local/mysql/my.cnf [link to sample my.cnf]
[client]
database = weatherapp
user = djangouser
password = ********
port = 15306
host = 127.0.0.1
default-character-set = utf8mb4Step 4 - Install MySQL Client Connector
$ pip install mysqlclient
Collecting mysqlclient
Using cached mysqlclient-2.0.1.tar.gz (87 kB)
Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed.
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient ... done
Successfully installed mysqlclient-2.0.1Step 5 - Build Django Framework over Vitess cluster
At this stage, weβre ready to run the migrations to create initial Django metadata.
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OKStep 6 - Create an admin user
Create an administrative user to access the Django Admin interface.
$ python manage.py createsuperuser
Username (leave blank to use 'askdba'): askdba
Email address: [email protected]
Password:
Password (again):
The password is too similar to the email address.
This password is too short. It must contain at least 8 characters.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
(env) askdba:weatherapp askdba$Step 7 - Start Django daemon.
$ python manage.py runserver 127.0.0.1:8000
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
October 16, 2020 - 09:37:02
Django version 3.1.2, using settings 'weatherapp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.Step 8 - Go to Django Admin page
Point your browser to http://127.0.0.1:8000/admin
<figcaption>Admin Login Screen</figcaption>
<figcaption>User/Role Management Screen</figcaption>You may continue to build the application from this point by following this example.
Conclusion
Vitess is a very powerful sharding framework that comes with a built-in control plane that allows backend developers to adapt their applications easily. Combining powerful application frameworks such as Django allows developers to create scalable applications out of the box with the power of open source tooling.
References
How To Make a Django Blog App and Connect it to MySQL
Getting Started With Django: Build A Weather App
File: content/en/blog/2020-12-15-vitess-at-kubecon-na.md
author: 'Deepthi Sigireddi' date: 2020-12-15 slug: '2020-12-15-vitess-at-kubecon-na' tags: ['Vitess','MySQL','conference'] title: 'Kubecon+CloudNativeCon NA 2020'
The Vitess team had a successful presence at Kubecon + CloudNativeCon North America 2020. This year's event was in a virtual format. It ran from Nov 17-20.
We had 2 talks, a project booth and 3 office hours sessions. In addition, we had mentions in 2 major keynote talks.
Day 1
Day 1 was a non-keynote day. It opened relatively quietly for us. We had 25+ attendees at our office hours session hosted by maintainers Alkin Tezuysal, Deepthi Sigireddi and Derek Perkins.
Some people wandered into the project booth.
<figcaption>Vitess Project Booth</figcaption>Day 2
This was our big day. Not only did we have both Vitess talks on this day, but we also had mentions in keynotes.
First, Priyanka Sharma, CNCF GM spoke about how HubSpot uses Vitess and Kubernetes.
<figcaption>Vitess + Kubernetes @ HubSpot</figcaption>Then, Constance Caramanolis, Conference Co-Chair, featured Vitess in the Project Updates Keynote.
<figcaption>Vitess Project Update</figcaption>Constance also featured Slack's Vitess migration as an End-User Story.
<figcaption>Vitess @ Slack</figcaption>Guido Iaquinti and Rafael Chacon of Slack spoke about how they migrated their MySQL Clusters into Vitess.
We wrapped up the day with the Vitess Maintainer talk which featured demos from a number of our maintainers.
Our project office hours featuring Sugu Sougoumarane and Rafael drew 120 attendees.
Day 3
Another quiet day. We had our monthly public meeting (Access Passcode: AKi00k&@) on this day, so we did not host office hours.
Day 4
We hosted our last project office hours with Alkin, Deepthi and Paul Hemberger. 65 people attended the session.
Project Booth
We had over 350 unique visitors to the project booth. We had maintainers available to answer questions but most visitors chose to view documents and not engage with the maintainers at the booth.
Thank you to everyone who attended the talks or visited the booth. Special thanks to our maintainer team for making all of this possible.
File: content/en/blog/2021-01-26-announcing-vitess-9.md
author: 'Alkin Tezuysal' date: 2021-01-26 slug: '2020-01-26-announcing-vitess-9' tags: ['release','Vitess','MySQL','kubernetes','operator','cloud','GKE','sharding'] title: 'Announcing Vitess 9'
On behalf of the Vitess maintainers team, I am pleased to announce the general availability of Vitess 9.
Major Themes
In this release, we have focused on making Vitess more stable after the successful release of Version 8. There have been no major issues reported. So there were no patches released for Version 8. This has allowed us to push further on compatibility and adoption of common frameworks as priorities. We have compiled all improvements into the Release Notes. Please read them carefully and report any issues via GitHub. We would like to highlight the following themes for this release:
Compatibility (MySQL, frameworks)
Our ongoing work is to make sure that Vitess accepts all queries that MySQL does. We continued to focus on SET and information_schema queries in this release as well as other common and complex queries. Several parts of the query serving module have been refactored to facilitate further compatibility enhancements.
Please note that reserved connections are still not on by default, and you should plan to test it first in a test environment, to ensure that all your queries and frameworks are supported, before enabling it in production.
Migration
Enhanced logging and metrics have been added to VReplication for helping to debug stalled and failing VReplication workflows and for increased visibility into other operational and performance-related issues.
VReplication support for JSON columns, which was previously incomplete, has been refactored and is now functionally complete.
A new version (v2) of the VReplication workflow CLI commands have been introduced. These incorporate functional and UX improvements based on user experience and feedback. These are deemed experimental (but fully functional) and we welcome feedback and suggestions on improving them further.
Innovation
There has been a significant push towards streamlining Online Schema Changes.
Changed syntax: The syntax for online DDL has been changed and finalized. We introduce the
@@ddl_strategysession variable, or the-ddl_strategycommand line flag to determine whether migration is executed normally (direct) or online (gh-ostorpt-osc). Further, migrations now use the standardALTER TABLEsyntax.Better auditing: A migration is now associated with a context as well as the identity of the issuing vttablet.
Better managed: Itβs possible to list migrations by context, to cancel all pending migrations. Vitess will automatically retry migrations that fail due to a failover.
More statements: Online DDL now also works for
CREATEandDROPstatements. This allows us to group together migrations with the same context.Safe, lazy and managed
DROPs: Online DDLDROPstatements are converted toRENAMEstatements, which send the tables to the lifecycle mechanism: tables are held for safekeeping for a period of time, then slowly and safely purged and dropped, without risking database lockdown. A multi-tableDROPstatement is exploded into distinct single-table operations.
As always, please validate any new features in your test environments before using them in production.
Documentation
Two new user guides have been created for new adopters of Vitess:
There is a shortlist of incompatible changes in this release. We encourage you to spend a moment reading the release notes and see if any of these will affect you.
Please download Vitess 9 and try it out!
File: content/en/blog/2021-02-22-online-ddl-in-vitess.md
author: 'Shlomi Noach' date: 2021-02-19 slug: '2021-02-19-online-ddl-in-vitess' tags: ['Vitess','MySQL', 'DDL', 'schema migrations', 'operations', 'gh-ost', 'percona toolkit', 'pt-online-schema-change'] title: 'Online DDL in Vitess'
Vitess introduces a new way to run schema migrations: non-blocking, asynchronous, scheduled online DDL. With online DDL Vitess simplifies the schema migration process by taking ownership of the operational overhead, and providing the user a simple, familiar interface: the standard ALTER TABLE statement.
Letβs first give some background and explain why schema migrations are such an issue in the databases world, and then dive into implementation details
The relational model and the operational overhead
The relational model is one of the longest surviving models in the software world, introduced decades ago and widely used until today. SQL is similarly old and solid, and you may find SQL or SQL-like languages even in non-relational databases.
The relational model makes sense for many common use cases, and entities with attributes (tables and columns, respectively) map well to popular constructs like users, products, memberships, messages, etc., and SQL is expressive enough to be able to construct both simple and complex questions.
But historically, the relational model came with a price. While many database systems optimize for reads and writes, they do not optimize as much for metadata changes, and in particular for schema changes. And one of the greatest challenges with such changes is that they require an operational undertaking, and are mostly outside the developerβs domain.
In the early days, it was common for database administrators (DBAs) to act like databasesβ bodyguards. They would hold off βcrazy requestsβ from developers. Requests for changes would go through lengthy procedures and paperwork.
Thankfully these days are mostly behind us, and we work more collaboratively with continuous deployments and rapid development. Alas, the new change intensifies the problem. In the old days, you'd make a schema change once a month; maybe even once in a few months. You'd plan for this, literally ship a new version for this. Today, it's not uncommon for the busiest database deployments in the world to run multiple schema migrations per day.
Which re-introduces and intensifies the schema migration problem: the process is mostly outside the domain of the developers. It requires them to be database experts. With multiple migrations per day it requires them to collaborate and sync with other developers in ways that are not compatible with their development flow (e.g. it's completely unlike comparing and merging git branches). In small companies, you'll see developers just owning and running their migrations as they see fit, but that doesn't scale, and the larger the product and organization, the more there's a need for a more formal flow.
In the MySQL world, direct schema migrations are blocking, if not on the primary then on replicas. Theyβre aggressive on resources and canβt be interrupted or throttled. Online schema change tools have been around for more than a decade, but they introduce their own complexity: youβd need to install them alongside the database, allow access, schedule the execution, login, execute, inform those tools on how to throttle, handle errors, provide visibility into their actions, and more. Itβs very common in companies of scale to have dedicated DBA or Ops teams who execute schema changes manually. These teams can spend hours per week or even per day by just handling the operational overhead of schema migrations.
For developers, this is a loss of ownership. While they own the idea of adding a column to some table, they need to request assistance from external teams, and often wait without much visibility into the state of progress. This breaks their flow. Perhaps one of the greatest appeals of NoSQL databases is that they donβt impose this level of constraint over a developerβs flow.
And for DBAs, schema migrations are a burden. An unexpected interruption from some developer to their own flow of work.
Some operational complexity
The operational overhead begins with the fact that a schema migration spans multiple domains. Letβs look at an incomplete breakdown of the schema migration flow:
- Formalizing: someone (developer?) needs to formalize the migration. Typically someone will come up with a
CREATE,DROP, orALTER TABLEstatement. Is this the correct statement? Is it syntactically valid? Does it conflict with existing conventions? - Discovery: where in production does this statement need to run? The developer may not be aware of how schemas are deployed across different clusters. Whatβs the discovery mechanism? And, given we found the correct cluster, which server acts as the primary for that cluster? Is the data sharded? If so, how do we detect all of the shards?
- Scheduling: is there already a migration running on desired clusters? Databases react poorly to concurrent migrations; better to run them in sequence. Do we need to wait? For how long? Will someone grab our slot if we go to sleep? Will we then lose another day of work?
- Execution: do we need to log in to some server? Where are we expected to run our online schema migration tools? What command line flags should we pass?
- Monitor: can we tell what the progress is? Can we make it visible for everyone to see? How do we inform interested parties when the migration is complete?
- Cleanup: schema migration tools for MySQL leave artifacts behind: large tables that need to be dropped. Dropping tables is in itself a problem. How do we automate the cleanup for those artifacts?
- Recovery: how do we proceed if migration failed? Is there an extra cleanup to be made?
With multiple clusters in production, some of which are sharded, what is the discovery mechanism for identifying the correct clusters, and those clusters' primaries, for applying schema changes?
Where Vitess fits in
Vitessβs architecture puts it in a unique position to address the majority of the schema migration flow. For example:
- Discovery is trivial. Vitess internally maps all schemas to shards and clusters, and knows, at any given time, where a migration (or any query, for that matter) should be applied.
- Vitess impersonates a monolithic database. Users access Vitess through vtgate, a smart proxy that understands queries, semantically. When Vitess intercepts a query, it does not strictly have to send the query to the backend database servers. With online DDL, Vitess takes note of the schema change request and schedules it for later.
The appropriate backend tablets will pick up that request, and will each schedule it to avoid running concurrent migrations. - The tablets execute online schema migration tools themselves. Today, Vitess supports
pt-online-schema-changeandgh-ost. The tablets decide how to execute those tools, provide the command line flags, any necessary hooks/plugins.
Moreover, on Linux/amd64gh-ostis precompiled and bundled with Vitess, so thereβs no need for installation.
Vitess instructs the tools to use its own internal throttling mechanism, so the tools donβt need to worry about which replicas to monitor. The throttling mechanism dynamically adapts to topology changes. - Vitess provides an interface to query migration progress, across all shards. In addition, it provides an interface for aborting a migration, or for retrying an aborted or a failed migration.
- Vitess understands which artifacts are generated by the schema migration tools. In fact, it instructs them on what artifacts to generate. Whether successful or failed, Vitess can clean up after the migration. It will send the artifact tables to the garbage collection mechanism. It will clean up leftover triggers for a
pt-oscmigration. Vitess creates a temporary account for each migration, and destroys it once migration is complete. - Vitess knows when a migration has failed and runs the appropriate cleanup, even if Vitess itself fails along with the migration. At this time Vitess offers a one-time auto-retry for a migration failure caused by a failover.
Vitess knows where schemas are deployed, what shards exist, who the primaries are at any given time, and can apply DDLs on the correct database servers without userβs intervention.
What does it look like to the user?
The objective in developing Vitessβs online DDL was to hide all that complexity from the user as much as possible. To that effect, all the user needs to run is:
SET @@ddl_strategy=βgh-ostβ;
ALTER TABLE my_table ADD COLUMN some_column INT NOT NULL;The ALTER TABLE statement itself is completely normal, but responds differently. It returns instantly, with a job ID with which the user can track the migrationβs progress. The user may choose between a gh-ost strategy, pt-osc strategy, or plain direct strategy (not an online DDL).
Where do we go from here?
There are many ways to proceed, short term and long term. Eventually, weβd want online DDL to work seamlessly across a resharding process. Also, it could work across a planned or unplanned reparent.
Online DDL is labeled experimental as we collect user feedback.
Please see the documentation on the Vitess website
Thereβs more...
Online DDL is not limited to ALTER TABLE statements. DROP TABLE statements suffer from locking issues, too. In a next blog post we will drill down into Vitess's table lifecycle, a garbage collector for unused tables.