VDesign a URL shortener. Where are the bottlenecks?
Вопрос интервьюераSystem Design
Единственно верного дизайна не существует. Интервьюеры оценивают, как вы уточняете задачу, как рассуждаете о цифрах и как объясняете компромиссы. Говорить в понятном порядке важнее, чем называть много технологий.
Используйте фиксированную структуру и проговаривайте её вслух: требования, прикидка цифр, простой дизайн, затем узкие места и масштабирование. Когда вы говорите "now I will estimate the load", интервьюер понимает, что вы делаете, а у вас появляется момент подумать.
- ✓Слова → фразы → предложения → речь
- ✓Смысл ответа
- ✓Язык
Частые вопросы и образцы ответов
Design a URL shortener. Where are the bottlenecks?
Спроектируйте сокращатель ссылок. Где узкие места?
Что хочет услышать интервьюер. Сначала уточняющие вопросы, потом простой дизайн, затем настоящее узкое место: чтение и уникальные коды.
Образец ответа на английском для тренировки вслухFirst I clarify the requirements: how many new links per day, how many redirects, and whether links expire. Let us say 100 million new links a month and a hundred times more reads. The design is simple: an API to create a link, a service that generates a unique short code, a database that maps the code to the URL, and a redirect service with a cache. Reads are the main load, so I put a cache in front of the database and use a store that scales for key-value access. The hard part is generating unique codes without collisions, for example with ranges of a counter given to each server, and base-62 encoding. I would also add rate limiting against abuse.
How do you structure your answer in a system design interview?
Как вы структурируете ответ на собеседовании по system design?
Что хочет услышать интервьюер. Повторяемый порядок, который вы проговариваете вслух.
Образец ответа на английском для тренировки вслухI follow the same order every time. First, I ask about requirements, both functional and non-functional, like latency and availability. Second, I make a rough estimate of the traffic and the storage, so I know the scale. Third, I draw a simple high-level design with the main components and the data model. Then I go deeper into the part that matters most, usually the data store or the bottleneck. At the end I discuss failure, monitoring and how the system can grow. I say each step aloud, so the interviewer can follow my thinking and guide me.
How would you use a cache, and what are the risks?
Как бы вы использовали кеш и какие у него риски?
Что хочет услышать интервьюер. Названный паттерн, срок жизни записей и минимум два реальных риска.
Образец ответа на английском для тренировки вслухI would use a cache for data that is read often and changes rarely. The most common pattern is cache-aside: the application checks the cache first, and on a miss it reads from the database and saves the result with a time to live. The risks are stale data, a cache stampede when a popular key expires and many requests hit the database together, and an unclear invalidation strategy. To reduce these risks, I choose a sensible expiry time, add a small random variation to it, and decide how much stale data the business accepts.
How do you scale a database?
Как масштабировать базу данных?
Что хочет услышать интервьюер. Разумный порядок: сначала простые шаги, затем реплики, затем шардирование с его ценой.
Образец ответа на английском для тренировки вслухI start with the simplest options: better indexes, query tuning and a bigger machine. Then I add read replicas, which help when reads dominate, but replicas can lag behind the primary. When writes or data size become the problem, I use sharding: splitting data by a key, such as a user ID, across several databases. Sharding brings complexity. Queries across shards are hard, and moving data between shards is painful. So I pick the shard key carefully and delay sharding until it is really needed.
How do you talk about trade-offs and consistency?
Как вы рассказываете о компромиссах и согласованности?
Что хочет услышать интервьюер. Каждое решение названо вместе с ценой и привязано к продукту.
Образец ответа на английском для тренировки вслухI try to say each decision together with its cost. For example, I choose eventual consistency for a news feed, because it gives lower latency and higher availability, and users can accept a delay of a few seconds. For payments, I choose strong consistency, because correctness is more important than speed. When a network partition happens, a distributed system must choose between consistency and availability, and I explain which one the business prefers for each part of the system. This shows that I think about the product, not only about technology.
Как произносить ключевые термины
- scalability
- скэйлэби́лити
- sharding
- ша́рдинг
- cache
- кэш
- availability
- эвэйлэби́лити
- latency
- лэ́йтэнси
- bottleneck
- бо́тлнек
Полезные фразы для ответа
- Let me clarify the requirements first.Давайте сначала уточним требования.
- Can I assume that…?Могу ли я предположить, что…?
- Let me do a rough estimate.Давайте сделаем грубую оценку.
- The main bottleneck here is…Главное узкое место здесь —…
- The trade-off is…, so I would choose…Компромисс такой:…, поэтому я бы выбрал…
- To summarise the design,Подведу итог по дизайну:
- If we have time, I would go deeper into…Если останется время, я бы углубился в…
Типичные ошибки
- Начинать рисовать, не задав вопросов. Первые минуты отдайте требованиям.
- Молчать, пока думаете. Скажите "I need a moment to think about the data model", чтобы интервьюер знал, что вы работаете.
- Называть много технологий без причин. Выберите одну и объясните, почему она подходит.
- Игнорировать сбои и мониторинг. Одно предложение о том, что происходит при падении узла, показывает опыт.
Частые вопросы
Нужны ли цифры на собеседовании по system design?
Да, приблизительные. Называйте их вслух: запросы в секунду, объём хранения за год. Они не обязаны быть точными, но показывают, что вы думаете о масштабе.
Что делать, если я не знаю технологию, которую назвал интервьюер?
Скажите об этом и рассуждайте от нужных вам свойств: "I have not used it, but if it is a key-value store with low latency, I would use it for…"
Как долго можно говорить без паузы?
Не больше минуты-двух. Останавливайтесь в естественных местах и спрашивайте: "Does this direction make sense to you?"
Прочитать ответ — не то же самое, что сказать его. Потренируйте каждый вопрос вслух, а затем сравните смысл и язык собственного ответа.
Попробовать SpeakRole ↗Другие темы в этом направлении