Python Module 16
Practical Python: text, CLIs, web, automation and security interview questions
Interview questions on “Practical Python: text, CLIs, web, automation and security”.
Warm-up questions
Short questions with short answers, each answered in full.
-
Fresher to mid
What is the difference between re.search(), re.match() and re.fullmatch()?
Answered in the lesson Regular expressions with the re module
-
Fresher to mid
What is the difference between textwrap.wrap(), textwrap.fill() and textwrap.shorten()?
Answered in the lesson Text tools: textwrap, difflib and string
-
Fresher to mid
What does a t-string evaluate to in Python 3.14, and how is it different from an f-string?
Answered in the lesson Template strings (t-strings) in Python 3.14
-
Fresher to mid
Why use the logging module instead of print() in an application?
Answered in the lesson Logging for scripts, applications and libraries
-
Fresher to mid
What exit status does an argparse program return on a usage error, and why does a command's exit status matter?
-
Fresher to mid
What is the difference between sys.platform and platform.system(), and how should a script check which Python version runs it?
Answered in the lesson Working with the OS: os, sys, shutil, platform
-
Fresher to mid
What do a dry run and idempotence mean for an automation script, and why do they matter for a script that runs on a schedule?
Answered in the lesson Automate office tasks: files, Excel, PDF, email
-
Fresher to mid
What does mainloop() do in a tkinter program, and why does a slow callback freeze the window?
Answered in the lesson Desktop GUIs with tkinter: a first app
-
Fresher to mid
When do you use the random module, and when the secrets module?
Answered in the lesson Secure tokens, password hashes and HMAC
-
Fresher to mid
In urllib, what is the difference between HTTPError and URLError, and in which order do you catch them?
Answered in the lesson Calling web APIs from Python with urllib
-
Fresher to mid
What does a WSGI server pass to your application, and what must the application return?
Answered in the lesson Serving HTTP: http.server and WSGI basics
-
Fresher to mid
If a site's robots.txt allows a path, may you scrape it?
Answered in the lesson Web scraping responsibly: robots.txt and parsing
-
Fresher to mid
What is the difference between a TCP socket and a UDP socket in Python?
Answered in the lesson Socket programming basics: TCP and UDP
Questions with model answers
What each question tests, the first step of a good answer and the follow-ups to expect.
-
Mid to senior
A sign-up form checks the name field with ^([A-Za-z]+ ?)+$. After a release, one request kept a worker at 100 % CPU for minutes and the queue backed up. Explain what happened, how you would prove it, and how you would fix the pattern and protect the service.
- What it tests
- Recognising catastrophic backtracking, reproducing it with growing input, rewriting a pattern without nested repetition, and layered defences such as input limits and timing tests.
- First step
- Reproduce it offline: time the pattern on a run of letters followed by a character it must reject, adding one letter at a time, and watch the time multiply. The cause is a repeated group whose inside also repeats, which gives the engine an exponential number of ways to fail.
- Follow-ups
-
- How do you rewrite the pattern without changing what it accepts?
- Would an atomic group or a possessive quantifier be enough?
- How do you protect the service if a slow pattern slips through again?
From the lesson Regular expressions with the re module
Model answer, Pro. Model answers open with any pass; prices are in the notice on this page.Opening the model answers with your pass…
Model answers open with any MySmartCoPilot pass.
- Pro pass · 1 week₹79$2.99
- 30 days₹179$5.99
- 1 year₹1,699$45
One payment; a pass never renews. The price shown is the total you pay: no fees or charges are added at checkout.
Passes can’t be bought right now, so the model answers can’t be opened at the moment. If you have a pass, enter your licence key.
It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).
In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A service receives about two million bank alert messages a day, in a few dozen formats, and must extract the amount, the date and a reference number from each. Would you use regular expressions? Describe how you would structure, test and monitor the extraction.
- What it tests
- Choosing regular expressions or a parser, organising many patterns, validating captured values, testing with real samples and near misses, and noticing format changes.
- First step
- Start from data: group a few thousand real messages by sender and format, and write one compiled, commented pattern per format with named groups. Regular expressions fit because each format is a short, regular line; parse what the groups capture with real parsers, such as Decimal for amounts.
- Follow-ups
-
- How do you test the patterns?
- A bank changes its message format. How do you detect it?
- How do you keep this fast at two million messages a day?
From the lesson Regular expressions with the re module
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A customer database holds 300,000 names with duplicates such as "Asha Kumari" and "ASHA KUMARI.". A colleague proposes comparing every pair with difflib.SequenceMatcher(None, a, b).ratio() > 0.9. Estimate the cost, say what would go wrong, and design a better approach.
- What it tests
- Estimating pairwise work, what SequenceMatcher scores measure, normalising text, blocking to cut comparisons, and choosing thresholds with labelled data.
- First step
- Count the pairs first: 300,000 names give about 45 billion pairs, so even 10 microseconds per score is more than five days of CPU time. Then point out that the raw score is case-sensitive and punctuation-sensitive, so the plan misses real duplicates while it scores different people as similar.
- Follow-ups
-
- Why not lower the threshold to catch more duplicates?
- Does the autojunk heuristic matter here?
- How would you do it inside a database?
From the lesson Text tools: textwrap, difflib and string
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Staff edit the wording of order-confirmation emails in an admin panel, and the code sends them with text.format(order=order, customer=customer). What is the risk, and how would you redesign how templates are stored, validated and rendered?
- What it tests
- Knowing that format fields read attributes, choosing string.Template, rendering from a chosen mapping, validating at save time and escaping for HTML.
- First step
- Name the risk: format fields can read attributes and items, so whoever edits the text can print any data reachable from the objects passed in. Then move to string.Template filled from a mapping of chosen values, and validate placeholders when the template is saved.
- Follow-ups
-
- Why not keep str.format and pass only a dictionary?
- How do you support translations?
- How do you test it?
From the lesson Text tools: textwrap, difflib and string
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
Design a tool that shows engineers what changed between two versions of a 5,000-line configuration file before a deploy, and flags risky changes such as ports, timeouts and debug switches. Which difflib functions do you use, and what else does the tool need?
- What it tests
- Using unified_diff for display, comparing parsed settings for the report, rules per key, masking secrets, CI exit statuses and difflib's behaviour on large files.
- First step
- Separate display from analysis: show a unified diff, which engineers know, but build the risk report by parsing both versions into settings and comparing keys, so reordered sections and comments do not hide or fake changes.
- Follow-ups
-
- How do you keep secrets out of the report?
- What if the file is not in a format you can parse?
- How do you make the output easy to read?
From the lesson Text tools: textwrap, difflib and string
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
A helper run_query(sql: str) is called as run_query(f"SELECT * FROM users WHERE email = '{email}'") all over a codebase that now runs on Python 3.14. Explain the risk, and design a replacement based on t-strings, including quoted placeholders, lists of values and table names.
- What it tests
- Recognising SQL injection, binding values through a t-string processor, refusing plain strings, and the edge cases of quoting, IN lists and identifiers.
- First step
- Name the risk: the value becomes part of the SQL text, so a crafted email adds conditions or statements. Then change the contract to run_query(query: Template), where a processor writes a placeholder for each value and passes the values as parameters, and refuses a plain str.
- Follow-ups
-
- Why not just escape quotes in the value?
- How can the processor cache its work?
- How do you test it?
From the lesson Template strings (t-strings) in Python 3.14
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Design a small HTML library for a dashboard in which all markup is built with t-strings. Which parts does it escape and which does it trust, how do nested components and attributes work, and how do you stop developers from bypassing the escaping by accident?
- What it tests
- Trusting written text and escaping values, nested templates, attribute and URL rules, and a single audited way to insert raw HTML.
- First step
- State the rule first: text written in code is trusted, values are not. Components return templates, one renderer escapes every value, and values that are templates are rendered recursively so nested components keep their tags.
- Follow-ups
-
- Why not use a format spec such as :safe for raw HTML?
- How do you handle attributes that may be absent?
- What about performance for big tables?
From the lesson Template strings (t-strings) in Python 3.14
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Senior to staff
Your team maintains a library that supports Python 3.10 to 3.14, and someone asks to switch to t-strings everywhere. What do you advise, what would you measure, and how would you introduce t-strings without breaking users on older versions?
- What it tests
- Knowing that t-strings are a syntax error before 3.14, choosing where they add safety, version-safe introduction, and measuring the processor's cost.
- First step
- Point out the compatibility problem first: on 3.13 and older a t-string makes the whole file a SyntaxError, so one literal in a shared module breaks every user on those versions. Then limit t-strings to code that builds HTML, SQL, commands or logs, where they add safety.
- Follow-ups
-
- How do you test both paths?
- What do you tell users?
- When can the library use t-strings freely?
From the lesson Template strings (t-strings) in Python 3.14
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
Users of your open-source library complain that importing it writes WARNING lines to their terminal, and that they cannot turn them off without patching your code. What is the library doing wrong, and what should its logging code look like?
- What it tests
- The split between libraries and applications, named loggers, NullHandler and the last-resort handler, choosing levels, and testing that a library is silent by default.
- First step
- Look for configuration inside the library: a basicConfig() call or a handler added at import time, log calls through the root logger, or no NullHandler, which lets Python's last-resort handler print warnings. Then state the rule: a library logs through named loggers and never configures logging.
- Follow-ups
-
- What if users really want output by default?
- How do you test it?
- What about warnings that users must see, such as a deprecated function?
From the lesson Logging for scripts, applications and libraries
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
After a refactor moved logging setup into a dictConfig() loaded from a TOML file, warnings from two modules stopped appearing in production while other modules still log, and nothing raised an error. How do you find the cause, and what do you change?
- What it tests
- Knowing what dictConfig() does to loggers that already exist, inspecting loggers at run time, and the other causes of missing lines, with a regression test.
- First step
- Start from what changed: the setup moved into dictConfig(), and only some modules went silent. Work out when each silent module creates its logger compared with when the configuration runs, then inspect those loggers' own attributes at run time before you touch any levels.
- Follow-ups
-
- What else can make lines disappear?
- Why does Python keep such a surprising default?
- How would you make logging configuration safer in general?
From the lesson Logging for scripts, applications and libraries
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Senior to staff
Design logging for a payments API that serves 2,000 requests a second across 30 instances: what each line contains, how a request id reaches every line, where secrets are removed, and how logging is kept from slowing requests down.
- What it tests
- Structured logs, volume estimates, propagating context with contextvars, redaction on handlers, queues for slow handlers, and operating logging at scale.
- First step
- Start from the reader: at this volume only machine-searchable logs help, so every line is one JSON object with a fixed core of fields and a request id. Then estimate the volume, a few lines per request at about 1 KB each, because it decides retention and sampling.
- Follow-ups
-
- How do you debug one customer's failing payments without turning on DEBUG everywhere?
- What happens when the log pipeline is down?
- How do you keep the format consistent across instances and services?
From the lesson Logging for scripts, applications and libraries
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
A backup command takes --source, --dest and --compress True or False with type=bool, opens files with argparse.FileType, prints errors with print() and always exits with status 0. What would you change in this design, and why?
- What it tests
- Spotting the type=bool trap, choosing positional arguments over required options, the FileType deprecation, standard error and exit statuses for scripts.
- First step
- Start with the option that can invert what the user asked for: work out what type=bool stores for --compress False, and replace it with a flag. Then move to the exit status, because a backup that always exits 0 can fail every night without anyone noticing.
- Follow-ups
-
- How would you prove the fixes with tests?
- Should the tool use click instead?
- What about a progress display?
From the lesson Command-line apps with argparse
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
How would you test a command-line tool with five subcommands built on argparse, so that the tests are fast, catch regressions in usage errors and exit statuses, and also prove that the installed command works?
- What it tests
- Structuring a CLI for testing, in-process parser and main() tests with argument lists, SystemExit codes, a subprocess smoke test and stable output across versions.
- First step
- Split the code into build_parser(), main(argv=None) that returns a status, and handlers that do the work. Then most tests can call parse_args() and main() with lists in the same process, without starting a new Python, and only one smoke test needs to start the installed command.
- Follow-ups
-
- How do you keep the help text from going stale?
- Why not test only through subprocesses?
- How do you test code that uses exit_on_error=False?
From the lesson Command-line apps with argparse
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
A command reads settings from a config file, environment variables and command-line options. Design how argparse fits in so that flags beat the environment, the environment beats the file and the file beats the defaults, help shows the effective values, and tests control every layer.
- What it tests
- Detecting given flags with default=None, merging layers in one place, consistent conversion and errors, showing sources, keeping secrets out of flags, and injectable layers for tests.
- First step
- Let argparse own only the top layer: declare every setting with default=None so None means not given, load the file and the environment into dictionaries, and merge the four layers in one function that takes the first value found for each key, flags first.
- Follow-ups
-
- Why not set the parser's defaults from the file and the environment?
- How do you handle secrets?
- What about boolean settings?
From the lesson Command-line apps with argparse
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A worker thread of a batch job calls sys.exit(1) when it finds corrupt input, yet the job's exit status is 0 and the scheduler reports success. Explain why, and how you would make the job fail correctly.
- What it tests
- What sys.exit() does inside a thread, how failures reach the main thread, and deciding a process's exit status in one place.
- First step
- Say what sys.exit() really does: it raises an exception, SystemExit, in the thread that calls it. Then follow that exception: which thread decides the exit status of the process, and does the exception ever reach it?
- Follow-ups
-
- How should the worker report the failure instead?
- The job uses a ThreadPoolExecutor. What changes?
- Why not call os._exit(1) from the worker?
From the lesson Working with the OS: os, sys, shutil, platform
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
You review a deployment script written on a Mac that must also run on Windows build servers. It joins paths with f-strings, splits PATH on ":", writes os.linesep to text files and calls rm -rf through a shell. What do you flag, and how do you test the fixes without a Windows machine?
- What it tests
- Recognising portability habits, their portable replacements in pathlib, os and shutil, and testing another platform's rules with pure paths and a CI matrix.
- First step
- Go habit by habit and ask what each one assumes about the operating system: the path separator, the separator between PATH entries, the line ending and the shell's commands. Then replace each assumption with the library call that knows the platform it runs on.
- Follow-ups
-
- How do you test Windows path rules on a Mac?
- What can pure paths not catch?
- Which environment-variable habit breaks the other way round?
From the lesson Working with the OS: os, sys, shutil, platform
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A service loads a C extension that sets TZ with setenv() at start-up. Child processes started by the service see the new TZ, but os.environ["TZ"] still shows the old value. Why, and what do you change?
- What it tests
- How os.environ is filled, how it can fall behind the real environment of the process, and passing environments to child processes on purpose.
- First step
- Ask where os.environ gets its values, and when. Then compare that moment with the moment the extension calls setenv(), and with what a child process receives when it starts.
- Follow-ups
-
- When is os.reload_environ() safe to call?
- How would you pass TZ to one child only?
- How do you test this behaviour?
From the lesson Working with the OS: os, sys, shutil, platform
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A scheduled script emails fee reminders to 2,000 parents every Monday at 07:00. Last week the mail server dropped the connection after 700 messages, the job was rerun, and 700 parents got the reminder twice. Redesign the job so that a crash and a rerun are safe.
- What it tests
- Idempotent sending with a send log, choosing between at-least-once and at-most-once, credentials and scheduling, and testing a crash without a mail server.
- First step
- Name what the rerun did not know: which messages the server had already accepted. Whatever the fix, the job has to remember that between runs, and decide what happens to the one message in flight when the connection drops.
- Follow-ups
-
- Should the log be written before or after each message is sent?
- The server's clock changes for daylight saving time. What can go wrong?
- How do you test the crash without a real mail server?
From the lesson Automate office tasks: files, Excel, PDF, email
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A nightly script renames scanned invoices in a shared folder to INV-<date>-<number>.pdf. One morning 40 invoices are missing, and the log shows no errors. What happened, and how do you make the script safe?
- What it tests
- Recognising silent overwrites by rename(), planning every name before acting, dry runs, logs that show clashes, and renames that are safe to run again.
- First step
- Look for files that wanted the same new name. Path.rename() replaces an existing target without a word on Linux and macOS, so each clash destroyed one invoice and still logged a success.
- Follow-ups
-
- How do you recover the lost invoices?
- How do you detect clashes before anything moves?
- What changes on Windows?
From the lesson Automate office tasks: files, Excel, PDF, email
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A web service lets schools upload .xlsx marks sheets of up to 100,000 rows. Some uploads crash the worker with out-of-memory errors, and dates sometimes come out four years early. Design the import.
- What it tests
- Treating uploads as untrusted, the memory cost of parsing a large sheet, how a workbook stores dates, and validating every value before it is saved.
- First step
- Treat the upload as untrusted input and check it before parsing it. Then estimate what parsing costs: how much memory one 100,000-row sheet needs when it is loaded whole, and whether it has to be loaded whole at all.
- Follow-ups
-
- Why do some dates come out four years early?
- How much memory should one import need?
- A formula column comes back empty. Why?
From the lesson Automate office tasks: files, Excel, PDF, email
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
A tkinter tool downloads a 200 MB report when the person clicks Fetch, and the window shows "Not Responding" for a minute. Redesign it so that the window stays responsive and shows progress.
- What it tests
- Why a callback blocks the event loop, moving waiting work to a worker thread, reporting through a queue polled with after(), and handling cancel and errors.
- First step
- Explain the freeze first: the download runs inside the button's callback, and while a callback runs the event loop handles nothing, not even redrawing. The download has to leave the callback, and then the window needs a way to hear about its progress.
- Follow-ups
-
- How does the worker report progress without touching widgets?
- How do you let the person cancel?
- What if the work were heavy computation instead of a download?
From the lesson Desktop GUIs with tkinter: a first app
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A colleague's tkinter app updates a label from a worker thread with label.config(text=...). It works on their laptop, but on another computer the app fails at random. What is wrong, and what do you change?
- What it tests
- Tk's threading model, what happens to calls from other threads, and how updates from workers should reach the window.
- First step
- Read what the tkinter documentation says about threads before you read the code: which thread a Tk object belongs to, and what happens to calls made from other threads. Then ask what was different on the colleague's laptop.
- Follow-ups
-
- Why did it work on the colleague's laptop?
- How should the worker send its updates?
- How do you check that no widget is touched off the main thread?
From the lesson Desktop GUIs with tkinter: a first app
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Your tkinter app has no tests, and every release breaks something in the window. Plan a test suite that runs on every push on a Linux CI server without a display.
- What it tests
- Separating logic from the window, driving widgets from code, what a hidden window can and cannot receive, and running Tk on a server.
- First step
- Split the suite by what each test needs. Move the calculations into plain functions and test them with no window at all; those tests run anywhere. Then decide how the window's wiring is tested, and what that part needs from the server.
- Follow-ups
-
- How do you test what the Return key does in the window?
- How do you give the CI server a display?
- What would you still check by hand?
From the lesson Desktop GUIs with tkinter: a first app
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A legacy app stores passwords as unsalted SHA-256 hex digests for 200,000 users. Plan the move to a proper password hash without forcing everyone to reset their password.
- What it tests
- Why fast unsalted hashes fail, choosing a key-derivation function and its settings, wrapping old hashes, upgrading at login, and retiring accounts that never return.
- First step
- Start with today's risk: a copied table of fast, unsalted hashes can be checked against lists of common passwords at enormous speed, and equal passwords stand out. Protect every stored hash at once by wrapping it in a slow, salted hash, rather than waiting for each user to log in.
- Follow-ups
-
- How exactly do you wrap the old hashes?
- Which settings would you choose, and how?
- What do you do about accounts that never log in again?
From the lesson Secure tokens, password hashes and HMAC
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Your payment webhook handler rejects every genuine notification with "signature mismatch", although the webhook secret is right. The web framework parses JSON before your code runs. Diagnose it and fix the handler.
- What it tests
- What an HMAC is computed over, what frameworks do to a request body, constant-time comparison, and idempotent handling of retried events.
- First step
- Compare what was signed with what you check: the exact bytes the gateway sent, or something rebuilt from them. Log both byte strings for one delivery, never the webhook secret, and look at the first place where they differ.
- Follow-ups
-
- How do you get the raw body in a framework that parses JSON?
- The same event arrives twice with valid signatures. What do you do?
- How do you rotate the webhook secret without losing notifications?
From the lesson Secure tokens, password hashes and HMAC
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Design one-time-code login by SMS for an app with 5 million users: how the code is made, stored and checked, and how you stop guessing.
- What it tests
- Secure random codes, the arithmetic of short codes, attempt limits and expiry, storing codes as hashes, constant-time checks, and rate limits per account and per source.
- First step
- Do the arithmetic first. Six digits are 1,000,000 values; with 5 attempts per code, a random guesser succeeds once in 200,000 codes. The code's strength comes from the attempt limit and the expiry, not from its length.
- Follow-ups
-
- Where do you store the code, and in what form?
- An attacker tries one guess on each of 100,000 accounts. What stops that?
- Why not send the same code again when the person asks for a new one?
From the lesson Secure tokens, password hashes and HMAC
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A nightly job calls a partner's API 3,000 times with urlopen(url, timeout=10) and usually finishes in 20 minutes. One night it ran for six hours, and no call raised TimeoutError. How can that happen, and how do you make the job finish on time?
- What it tests
- What a socket timeout limits, slow responses that never trip it, deadlines per call and per job, retry budgets, and how logs and metrics would have shown the problem early.
- First step
- Start from what timeout=10 means: it limits each blocking wait, the connection and every read, not the whole call, so a server that sends a byte every few seconds never trips it. Then estimate: 3,000 calls that take 7 seconds instead of 0.4 add about five and a half hours.
- Follow-ups
-
- How do you enforce a deadline on the whole call?
- Where else can the time go, besides slow responses?
- How would you have noticed it before morning?
From the lesson Calling web APIs from Python with urllib
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Your service retries failed calls to a payment API three times with no delay. During the partner's outage your request rate to them quadrupled, and some customers were charged twice. What went wrong, and how do you redesign the retries?
- What it tests
- Retry amplification, which methods are safe to repeat, idempotency keys, backoff with jitter, Retry-After, and retry budgets or circuit breakers for long outages.
- First step
- Name the two faults apart. Immediate retries multiply load: every failed call becomes four, which is the fourfold rate the partner saw. Repeating a payment POST without a key resends a request that may already have succeeded, so a timeout after the charge turns into a second charge.
- Follow-ups
-
- How does an idempotency key work from end to end?
- How long should the waits be, and when do you stop?
- What do you do when the partner stays down for an hour?
From the lesson Calling web APIs from Python with urllib
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to staff
A chat app fetches a preview of every link users post. A security report says the preview service can be pointed at internal addresses. How do you fix it, and how do you prove that the fix works?
- What it tests
- Server-side request forgery in code you own: allowed schemes and ports, checking every resolved address, redirects, DNS answers that change, network rules, and tests that fail on the old check.
- First step
- Find every place where the service turns text from a user into a connection, and define a safe destination: https on port 443 to public addresses only. Then check the address the connection will use, not the text of the URL, because names and number spellings can point inside the network.
- Follow-ups
-
- What do you do about redirects?
- How do you stop a name that resolves differently the second time?
- Which tests would you add to the build?
From the lesson Calling web APIs from Python with urllib
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
A teammate ran python -m http.server in the project folder at a hackathon to show a build to one judge, and left it running all afternoon. The terminal log shows requests from 40 addresses, some for files outside the build. What was exposed, and what do you do now?
- What it tests
- The default bind address, what the handler serves, symbolic links, reading the access log, rotating secrets and a safer way to share files.
- First step
- Name what the command did: without --bind it listened on every interface of the laptop, with no login, and it served the folder it ran in and everything below it. Then read the log before anything else: which paths were answered with 200, and from which addresses.
- Follow-ups
-
- How do you find out what was taken?
- Why did paths outside the build work?
- What would you use instead next time?
From the lesson Serving HTTP: http.server and WSGI basics
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Users with Hindi and Tamil names say your WSGI JSON API sometimes returns cut-off answers, while English names always work. The app sets Content-Length itself. Find the cause, fix it, and say which test would have caught it.
- What it tests
- Bytes against characters in Content-Length, UTF-8 lengths, what a client does with a wrong length, persistent connections, and tests that use data outside ASCII.
- First step
- Compare the header with the body on the wire for one failing user: count the characters of the name and its bytes in UTF-8. नमस्ते is 6 characters and 18 bytes, so a header computed from the characters tells the client to stop after a third of the body.
- Follow-ups
-
- Why did the tests pass?
- What happens to the extra bytes on a connection that stays open?
- Which test would have caught it?
From the lesson Serving HTTP: http.server and WSGI basics
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
A WSGI service on nine sync workers handles 200 requests a second at 40 ms each. When 20 students upload 2 MB photos from slow phones at 50 KB a second, every other page times out while the CPU stays at 10 %. Explain what is happening and how you fix it.
- What it tests
- How a sync worker is held by a slow client, capacity arithmetic, buffering proxies, request size limits and timeouts at each layer.
- First step
- Do the arithmetic. A 2 MB upload at 50 KB a second holds a worker for 40 seconds, in which it could have answered 1,000 normal requests. Twenty such uploads are more than the nine workers there are, so every other request waits in the queue while the CPU idles.
- Follow-ups
-
- Why does a buffering proxy fix it?
- Would more workers help?
- What limits would you set, and where?
From the lesson Serving HTTP: http.server and WSGI basics
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A price tracker you wrote fetches 2,000 product pages an hour from one shop. The shop first answered some requests with 429, and a week later answers every request with 403. Explain why, and redesign the tracker so that it can run again with the shop's agreement.
- What it tests
- Reading 429 and 403 correctly, load arithmetic, fetching by change with sitemaps, ETags and feeds, backing off, and stopping and asking instead of evading a block.
- First step
- Work out what the shop sees: 2,000 pages an hour is 48,000 requests a day, one every 1.8 seconds, mostly for prices that did not change. The 429 answers asked the tracker to slow down; it did not, so the shop refused it with 403, which is a decision to respect and not an error to retry.
- Follow-ups
-
- How do you find out which pages changed without fetching them all?
- What do you do about the 403?
- How do you keep the data fresh enough for price alerts?
From the lesson Web scraping responsibly: robots.txt and parsing
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to senior
Your scraper for a college's results table ran every night. After the college redesigned its site, the scraper kept running and saved empty names for a week before anyone noticed. Explain what failed, and how you make the next redesign fail loudly and recover quickly.
- What it tests
- Silent failures in parsers, checking the shape and the values of extracted data, comparing runs, alerts with saved pages, fixture tests and recovering bad data.
- First step
- Separate the two failures: the parser kept producing rows from a page whose structure had changed, and nothing checked the rows against what results must look like. A week of silence means the checks were missing, so a better parser alone would fail the same way at the next redesign.
- Follow-ups
-
- Which checks would have caught it on the first day?
- How do you test the parser before the site changes?
- What do you do with the week of bad data?
From the lesson Web scraping responsibly: robots.txt and parsing
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A crawler obeys robots.txt on your laptop but fetches paths the file disallows in production. Both run Python 3.14 and the site's file has not changed. Find the likely cause, show how you would confirm it, and make the crawler safe against a repeat.
- What it tests
- How urllib.robotparser matching changed within the 3.14 series, longest-match and pattern rules, reproducing a difference on two versions, start-up self-checks and pinning versions.
- First step
- Ask the parser the same questions on both machines: take the site's robots.txt and the paths that the production log shows, call can_fetch() for each on both Pythons, and print sys.version beside the answers. A difference in the answers points at the parser, not at the site.
- Follow-ups
-
- Which change in Python explains it?
- How do you make the crawler refuse to run on a parser that disagrees?
- Why did the tests not catch it?
From the lesson Web scraping responsibly: robots.txt and parsing
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Fresher to mid
A client sends JSON messages over TCP and reads each reply with one recv(4096) followed by json.loads(). It passes every test on a laptop but now and then fails in production with half a message or extra data. Explain why, and rewrite the reading.
- What it tests
- TCP as a stream, partial and merged reads, framing by length or newline, size limits and timeouts, and tests that split messages on purpose.
- First step
- Recall what TCP promises: bytes in order, with no message boundaries. recv(4096) returns whatever has arrived, so on one machine a short message usually comes whole, and across a network a 10,000-byte one comes in pieces. The fix is to mark where a message ends and to read until it does.
- Follow-ups
-
- Which framing would you choose, and why?
- How do you test it without a slow network?
- What limits does the reader need?
From the lesson Socket programming basics: TCP and UDP
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
A TCP server accepts one client at a time and reads from it until it closes. Once a day it stops answering everyone, although the process is alive and the CPU is idle. Find the cause, fix the server, and describe the test that would have shown it.
- What it tests
- Blocking calls without timeouts, what waits in the listen queue, serving connections concurrently, idle and message deadlines, connection limits and a regression test.
- First step
- Find the call the process is waiting in: a blocking recv() on one connection. With no timeout and one loop, a single client that connects and sends nothing holds the only thread, and every other client waits in the listen queue. Reproduce it with two clients on 127.0.0.1 before changing anything.
- Follow-ups
-
- Which way of serving several clients would you pick?
- What timeouts and limits does the server need?
- How do you reproduce the problem in a test?
From the lesson Socket programming basics: TCP and UDP
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
An app sends one UDP datagram per event to a metrics collector. At peak hours the dashboards show 15 % fewer orders than the database does, and no errors appear anywhere. Explain what is happening and what you change.
- What it tests
- What UDP promises, gauges against counted events, where datagrams are lost, finding loss with sequence numbers, aggregating, tuning buffers and moving exact counts to a reliable path.
- First step
- Say what UDP promises: nothing about delivery, and the sender gets no error when a datagram is lost. Then ask what the metric is. A gauge such as memory in use survives a 15 % loss; counted events such as orders do not, because every total on the dashboard comes out wrong.
- Follow-ups
-
- How do you find out where the datagrams are lost?
- What changes would reduce the loss?
- When should these metrics move off UDP?
From the lesson Socket programming basics: TCP and UDP
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes