{"groups":[{"k":"lang","name":"Programming languages","name_es":"Lenguajes de programación"},{"k":"web","name":"Backend & web","name_es":"Backend y web"},{"k":"data","name":"Data & databases","name_es":"Datos y bases de datos"},{"k":"cloud","name":"Cloud & DevOps","name_es":"Cloud y DevOps"},{"k":"cs","name":"Computer science & design","name_es":"Informática y diseño"},{"k":"qs","name":"Quality & security","name_es":"Calidad y seguridad"},{"k":"team","name":"Teamwork & career","name_es":"Equipo y carrera"}],"topics":[{"k":"py","g":"lang","name":"Python","name_es":"Python","p":"PY"},{"k":"jv","g":"lang","name":"Java Core","name_es":"Java Core","p":"JV"},{"k":"spr","g":"web","name":"Spring, JPA & Java Web","name_es":"Spring, JPA y Java Web","p":"SPR"},{"k":"oop","g":"cs","name":"Design & Practices","name_es":"Diseño y buenas prácticas","p":"DP"},{"k":"api","g":"web","name":"Backend & APIs","name_es":"Backend y APIs","p":"API"},{"k":"db","g":"data","name":"Databases & SQL","name_es":"Bases de datos y SQL","p":"DB"},{"k":"algo","g":"cs","name":"Algorithms & DS","name_es":"Algoritmos y estructuras de datos","p":"ALG"},{"k":"sys","g":"cs","name":"System Design","name_es":"Diseño de sistemas","p":"SD"},{"k":"sec","g":"qs","name":"Security","name_es":"Seguridad","p":"SEC"},{"k":"fe","g":"web","name":"Frontend & Web","name_es":"Frontend y web","p":"FE"},{"k":"ops","g":"cloud","name":"Cloud & DevOps","name_es":"Cloud y DevOps","p":"OPS"},{"k":"vcs","g":"team","name":"Maven, Git & SDLC","name_es":"Maven, Git y SDLC","p":"VCS"},{"k":"test","g":"qs","name":"Testing","name_es":"Testing","p":"TST"},{"k":"beh","g":"team","name":"Behavioral","name_es":"Preguntas de comportamiento","p":"BEH"}],"questions":[{"id":"PY-01","t":"m","l":2,"q":"In CPython (default build, GIL enabled), which workload gets a real speedup from `threading`?","o":["CPU-bound pure-Python work, like resizing images in a loop","I/O-bound work, like hundreds of concurrent HTTP requests","Both kinds of work get the same speedup from extra threads","Neither kind: extra threads never speed up Python code"],"a":1,"e":"The GIL (Global Interpreter Lock) is a lock inside CPython that lets only ONE thread run Python code at any moment.\nFor calculations (CPU work), extra threads just take turns, so the job does not finish faster.\nBut when a thread waits for the network or the disk, it releases the GIL and another thread can run. With 100 HTTP requests most of the time is waiting, so threads overlap that waiting and the total time drops a lot.","r":"Threads help when you wait (I/O). For heavy computation, use several processes.","g":["gil","thread","process","io_bound","cpu_bound","http"],"fa":"I/O-bound work such as hundreds of concurrent HTTP requests","cat":"py"},{"id":"PY-02","t":"m","l":2,"q":"What does this print?","c":"def add(item, bucket=[]):\n    bucket.append(item)\n    return bucket\n\nadd(1)\nprint(add(2))","o":["[2]","[1, 2]","TypeError","[[1], [2]]"],"a":1,"e":"Python creates a default value only ONCE, when the `def` line runs, not on every call.\nHere the default is one single list object. Every call that does not pass `bucket` reuses that same list: the first call adds 1, the second adds 2 to the same list, so it prints [1, 2].\nFix: use `None` as the default and create a new list inside the function.","ec":"def add(item, bucket=None):\n    if bucket is None:\n        bucket = []\n    bucket.append(item)\n    return bucket","r":"Never use [], {} or set() as a default argument.","g":["mutable","default_arg","function","identity"],"cat":"py"},{"id":"PY-03","t":"m","l":3,"q":"What does this print?","c":"fns = [lambda: i for i in range(3)]\nprint([f() for f in fns])","o":["[0, 1, 2]","[2, 2, 2]","[3, 3, 3]","NameError"],"a":1,"e":"Each lambda does NOT save the value of `i` when it is created. It saves a link to the variable `i` and reads it later, when it is called (this is called late binding).\nWhen we call the lambdas, the loop has already finished and `i` is 2, so all of them return 2.\nFix: capture the current value as a default argument, which is evaluated immediately.","ec":"fns = [lambda i=i: i for i in range(3)]   # [0, 1, 2]","r":"Closures remember variables, not values.","g":["closure","lambda","scope","default_arg"],"cat":"py"},{"id":"PY-04","t":"m","l":1,"q":"What does this print?","c":"a = [1, 2]\nb = [1, 2]\nprint(a == b, a is b)","o":["True True","True False","False False","False True"],"a":1,"e":"`==` asks: do both objects contain the same value? `is` asks: are they literally the same object in memory?\n`a` and `b` are two different lists that happen to contain the same numbers, so `==` is True and `is` is False.\nUse `is` only to compare with singletons like None: `if x is None:`.","r":"== compares values, is compares identity.","g":["identity","object","immutable","hash","singleton"],"cat":"py"},{"id":"PY-05","t":"m","l":2,"q":"What does this print?","c":"g = (x for x in range(3))\nprint(list(g), list(g))","o":["[0, 1, 2] [0, 1, 2]","[0, 1, 2] []","[] []","TypeError"],"a":1,"e":"A generator produces values one at a time and does not keep them. Once you have read them all it is 'exhausted' and cannot start again.\nThe first `list(g)` reads 0, 1, 2. The second finds nothing left and returns [].\nIf you need the data twice, store it in a list first.","r":"Generators are single-use.","g":["generator","iterator","n_yield","lazy","n_iter_next"],"cat":"py"},{"id":"PY-06","t":"m","l":2,"q":"`sum(x * x for x in range(10**8))` versus `sum([x * x for x in range(10**8)])`. What is the key difference?","o":["The generator version is always faster because it skips the loop","The generator version holds one item at a time, so memory stays flat","Both versions are identical after Python compiles them to bytecode","The list version is lazy and only builds values when sum asks"],"a":1,"e":"With square brackets `[...]` Python first builds a complete list of 100 million numbers in memory, and only then `sum` adds them.\nWith parentheses `(...)` it is a generator expression: each number is created only when `sum` asks for the next one, so only one number exists at a time.\nSame result, far less memory.","r":"Use generators for big data you only loop over once.","g":["generator","lazy","list_comprehension"],"fa":"The generator version uses roughly constant memory; the list version builds 100M items first","cat":"py"},{"id":"PY-07","t":"m","l":2,"q":"Why use `functools.wraps` inside a decorator?","o":["It makes the wrapper run faster by skipping one function call","It copies `__name__` and `__doc__` from the original function","It lets the decorator accept arguments when it is applied to code","It caches the result of the function between two calls"],"a":1,"e":"A decorator replaces your function with a new one (the wrapper). Without `@wraps`, the result looks like the wrapper: its name becomes 'wrapper' and your docstring disappears.\nThat confuses logs, debuggers, documentation tools and frameworks that use the function name.\n`@functools.wraps(func)` copies the name, docstring and other metadata from the original function to the wrapper.","r":"Always put @functools.wraps(func) on the inner wrapper.","g":["decorator","metadata","n_wraps"],"fa":"It copies metadata (`__name__`, `__doc__`, `__wrapped__`) from the original function onto the wrapper","cat":"py"},{"id":"PY-08","t":"m","l":3,"q":"A typical implementation of a decorator used as `@retry(times=3)` needs how many nested callables?","o":["1","2","3","4"],"a":2,"e":"`@retry(times=3)` first CALLS `retry(3)`. That call must return a decorator.\nThe decorator receives your function and returns a wrapper.\nThe wrapper runs every time your function is called.\nSo there are three levels: retry (settings) → decorator (function) → wrapper (call arguments).","ec":"def retry(times):\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            for attempt in range(times):\n                try:\n                    return func(*args, **kwargs)\n                except Exception:\n                    if attempt == times - 1:\n                        raise\n        return wrapper\n    return decorator","r":"A decorator with arguments is a function that returns a decorator.","g":["decorator","closure","higher_order"],"cat":"py"},{"id":"PY-09","t":"m","l":3,"q":"What does this print?","c":"class A:\n    def hi(self): return \"A\"\nclass B(A):\n    def hi(self): return \"B\"\nclass C(A):\n    def hi(self): return \"C\"\nclass D(B, C):\n    pass\n\nprint(D().hi(), [k.__name__ for k in D.__mro__])","o":["B ['D', 'B', 'C', 'A', 'object']","C ['D', 'C', 'B', 'A', 'object']","B ['D', 'B', 'A', 'C', 'object']","A ['D', 'A', 'B', 'C', 'object']"],"a":0,"e":"When a class has several parents, Python needs a fixed order to search for methods. That order is the MRO (Method Resolution Order).\nPython builds it with an algorithm called C3: the class itself first, then the parents from left to right, and a shared grandparent (A) only after all of its children.\nFor D that is D, B, C, A, object. B is the first class with `hi()`, so it prints B.","r":"Python searches parents left to right; check the order with Class.__mro__.","g":["mro","inheritance","multiple_inheritance","class","method","attribute"],"cat":"py"},{"id":"PY-10","t":"m","l":3,"q":"What is the main effect of defining `__slots__ = (\"x\", \"y\")` in a class?","o":["It makes instances immutable, so no attribute can be reassigned","It drops the per-instance `__dict__`, saving memory and fixing the attributes","It makes the class thread-safe by locking every attribute access","It turns the class into a dataclass with generated methods"],"a":1,"e":"Normally each object keeps its attributes in its own dictionary (`__dict__`), which costs memory.\nWith `__slots__`, Python reserves fixed spaces only for the listed names and removes that dictionary.\nResult: less memory per object (useful when you have millions of them), and you cannot add other attributes by mistake.","r":"__slots__ = less memory and a fixed set of attributes.","g":["attribute","slots","instance","class","object","property"],"fa":"Removes the per-instance `__dict__`, saving memory and blocking new attributes","cat":"py"},{"id":"PY-11","t":"m","l":3,"q":"A class defines `__eq__` but not `__hash__`. What happens when you add an instance to a `set`?","o":["It uses the default identity hash","TypeError: unhashable type","It works but duplicates are allowed","It uses `__eq__` to compute a hash"],"a":1,"e":"Sets and dictionary keys find objects by their hash (a number calculated from the object).\nThe rule is: equal objects must have the same hash. When you write your own `__eq__`, Python cannot be sure the old hash still follows that rule, so it sets `__hash__ = None`.\nThe object becomes unhashable and adding it to a set raises TypeError. Define `__hash__` using the same fields you compare in `__eq__`.","r":"Override __eq__ → also define __hash__ if you need sets or dict keys.","g":["hash","set","dunder","n_eq_hash","n_builtin_exc"],"cat":"py"},{"id":"PY-12","t":"m","l":2,"q":"`print([obj])` where `obj` defines both `__str__` and `__repr__`. Which one is used for `obj`?","o":["`__str__`","`__repr__`","`__format__`","Neither: it prints the memory address"],"a":1,"e":"`__str__` returns friendly text for users. `__repr__` returns precise text for developers.\nWhen Python prints a list, it shows each element with `repr()`, because it wants unambiguous output.\nSo `print([obj])` uses `__repr__`, while `print(obj)` uses `__str__`.","r":"Containers show their items with repr().","g":["dunder","repr","n_init","object","class"],"cat":"py"},{"id":"PY-13","t":"m","l":3,"q":"In a context manager, what happens if `__exit__` returns `True`?","o":["The `with` block is executed again from the beginning","Any exception raised inside the block is suppressed","The resource stays open until the program ends","`__enter__` is called again to restore the resource"],"a":1,"e":"A context manager (what you use with `with`) has `__enter__`, which runs at the start, and `__exit__`, which runs at the end, even when there is an error.\nIf an exception happens inside the block, Python passes it to `__exit__`. If `__exit__` returns True, Python considers the error handled and does not raise it.\nReturning False or None lets the error continue.","r":"__exit__ returning True swallows the exception.","g":["context_manager","exception","n_enter_exit"],"cat":"py"},{"id":"PY-14","t":"m","l":2,"q":"Inside an `async def` FastAPI endpoint you call `time.sleep(2)` (or `requests.get`). What happens under load?","o":["Only that request waits 2 seconds; other requests keep running","The event loop is blocked, so every other request on that worker stalls","FastAPI moves the blocking call to a separate thread automatically","Python raises an error because blocking calls are not allowed"],"a":1,"e":"An async server uses ONE thread with an event loop. The loop switches to other requests whenever the current one is waiting at an `await`.\n`time.sleep` and `requests.get` wait without `await`, so the loop cannot switch: the thread is frozen and every other user waits too.\nUse async versions (`await asyncio.sleep`, `httpx.AsyncClient`) or declare the endpoint with plain `def`, which FastAPI runs in a separate thread.","r":"Never call blocking code inside async def.","g":["event_loop","coroutine","blocking","async_await","n_sleep"],"fa":"The whole event loop is blocked; every other request on that worker stalls","cat":"py"},{"id":"PY-15","t":"m","l":2,"q":"Roughly how long does `main()` take?","c":"import asyncio\n\nasync def main():\n    await asyncio.sleep(1)\n    await asyncio.sleep(1)\n    await asyncio.sleep(1)\n\nasyncio.run(main())","o":["~1 second","~3 seconds","~0 seconds","It never finishes"],"a":1,"e":"`await` means: wait here until this finishes, then continue to the next line.\nThe three sleeps therefore run one after another: 1 + 1 + 1 = 3 seconds.\nTo run them at the same time, start them together with `asyncio.gather`; then they wait in parallel and the total is about 1 second.","ec":"await asyncio.gather(\n    asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1)\n)   # ~1 second","r":"Separate awaits run in sequence; gather runs them concurrently.","g":["async_await","concurrency","n_sleep","n_gather"],"cat":"py"},{"id":"PY-16","t":"m","l":2,"q":"Inside a coroutine you write `asyncio.sleep(1)` without `await`. What happens?","o":["The sleep runs in the background while the coroutine continues","It creates a coroutine object that never runs, plus a warning","It blocks the whole event loop for one second, then continues","Python raises a SyntaxError because `await` is required there"],"a":1,"e":"Calling an async function does not run its code. It only creates a coroutine object, like a recipe that nobody cooks.\nThe code runs only when you `await` it or schedule it with `asyncio.create_task(...)`.\nPython prints a 'never awaited' warning to help you find this bug.","r":"Calling an async function returns a coroutine; nothing runs until it is awaited.","g":["coroutine","async_await","n_sleep"],"fa":"A coroutine object is created and never run; Python warns 'coroutine was never awaited'","cat":"py"},{"id":"PY-17","t":"m","l":3,"q":"Two objects reference each other and nothing else references them. What frees them in CPython?","o":["Reference counting frees them immediately, since both are unused","The cyclic garbage collector, from the `gc` module, finds and frees them","Nothing frees them, so they stay in memory until the program exits","The operating system reclaims them when the thread finishes"],"a":1,"e":"CPython mainly frees memory with reference counting: every object counts how many references point to it, and when the count reaches 0 it is deleted at once.\nIn a cycle (A points to B and B points to A) the counts never reach 0, even if the rest of the program no longer uses them.\nA second mechanism, the cyclic garbage collector, runs from time to time, finds these unreachable groups and frees them.","r":"Reference counting frees most objects; the gc cleans up cycles.","g":["reference_counting","garbage_collector","object","class"],"fa":"The cyclic garbage collector (`gc` module)","cat":"py"},{"id":"PY-18","t":"m","l":2,"q":"What does this print?","c":"import copy\na = [[1], [2]]\nb = copy.copy(a)\nb[0].append(9)\nprint(a)","o":["[[1], [2]]","[[1, 9], [2]]","[[1], [2], 9]","[[9], [2]]"],"a":1,"e":"`copy.copy` creates a new outer list, but the items inside are the SAME inner lists, not copies.\nSo `b[0]` and `a[0]` are one and the same list; appending to it shows up in both.\n`copy.deepcopy` copies everything recursively, so nothing is shared.","r":"Shallow copy = new container, same contents.","g":["shallow_copy","deep_copy","mutable"],"cat":"py"},{"id":"PY-19","t":"m","l":2,"q":"Since which Python version is insertion order of `dict` guaranteed by the language spec?","o":["2.7","3.5","3.7","3.10"],"a":2,"e":"Since Python 3.7 the language guarantees that a dict remembers the order in which keys were added, and loops return keys in that order.\nCPython 3.6 already did this, but only as an implementation detail you could not rely on.","r":"Dicts keep insertion order (3.7+).","g":["dict","n_dict_order","hash_table","hash","mutable"],"cat":"py"},{"id":"PY-20","t":"m","l":3,"q":"Which typing tool lets a type checker accept any object that has a `read()` method, without inheritance?","o":["`typing.Protocol`","`abc.ABC`","`typing.TypeVar`","`typing.Final`"],"a":0,"e":"There are two ways to decide that a type is compatible. Nominal: the class must inherit from a base class (like an ABC). Structural: the class only needs the right methods (duck typing).\n`typing.Protocol` gives type checkers structural typing: any object with a `read()` method matches a Protocol that declares `read()`, without inheriting from anything.","r":"Protocol = duck typing that type checkers understand.","g":["protocol","duck_typing","type_hint","abc","structural_typing"],"cat":"py"},{"id":"PY-21","t":"m","l":3,"q":"What does `T` achieve here?","c":"from typing import TypeVar\nT = TypeVar(\"T\")\n\ndef first(items: list[T]) -> T:\n    return items[0]","o":["It makes the function run faster by caching the first element","It ties the return type to the element type: `list[int]` gives `int`","It lets the function return any type, whatever the input is","It enforces the types at runtime and raises an error on mismatch"],"a":1,"e":"A TypeVar is a placeholder for a type, like a variable but for types.\n`list[T] -> T` says: whatever type is inside the list, the function returns that same type. A type checker then knows `first([1, 2])` is an int and `first([\"a\"])` is a str.\nPython itself does not check this when running; tools like mypy or pyright do.","r":"TypeVar links the input type to the output type.","g":["type_hint","generic","n_typevar","protocol","class","function"],"fa":"It ties the return type to the element type: `list[int]` returns `int`","cat":"py"},{"id":"PY-22","t":"m","l":2,"q":"What happens with `f(1, 2)`?","c":"def f(a, *, b):\n    return a + b","o":["It returns 3, because both arguments are added together","TypeError: the function takes 1 positional argument but 2 were given","It runs, with `b` set to None because it was not named","SyntaxError, because a bare `*` is not allowed in a definition"],"a":1,"e":"Every parameter after a lone `*` must be passed by name (keyword-only).\n`b` is after the `*`, so `f(1, 2)` fails: the function accepts only one positional argument. The correct call is `f(1, b=2)`.\nThis makes calls clearer. Parameters before a `/` are the opposite: positional-only.","r":"After * → keyword-only. Before / → positional-only.","g":["keyword_arg","positional_arg","function","z_parameter","default_arg","n_builtin_exc"],"fa":"TypeError: takes 1 positional argument but 2 were given","cat":"py"},{"id":"PY-23","t":"m","l":2,"q":"What does `@dataclass(frozen=True)` give you (with default `eq=True`)?","o":["Mutable instances with a generated `__hash__`","Immutable instances that are also hashable","Instances that cannot be compared","Automatic validation of field types"],"a":1,"e":"`@dataclass` writes `__init__`, `__repr__` and `__eq__` for you from the list of fields.\n`frozen=True` makes objects read-only: changing a field raises an error.\nBecause a frozen object never changes, its hash stays valid, so Python also creates `__hash__` and you can use the object in sets or as a dict key. Note: dataclasses do not validate types (Pydantic does).","r":"frozen dataclass = immutable + hashable.","g":["dataclass","immutable","hash","n_init","n_eq_hash"],"cat":"py"},{"id":"PY-24","t":"m","l":3,"q":"`@property` is built on which mechanism?","o":["Metaclasses, which rewrite the class when it is created","The descriptor protocol, using `__get__` and `__set__`","The `__getattr__` fallback, called for missing attributes","Closures, which keep the getter's variables alive"],"a":1,"e":"A descriptor is an object that controls what happens when an attribute is read or written, by defining `__get__`, `__set__` or `__delete__`.\n`property` is a built-in descriptor: reading `obj.x` calls your getter function.\nThe same mechanism makes methods, classmethods and ORM columns (like SQLAlchemy fields) work.","r":"@property is a descriptor.","g":["descriptor","property","attribute","orm"],"fa":"The descriptor protocol (`__get__` / `__set__`)","cat":"py"},{"id":"PY-25","t":"m","l":3,"q":"What does `type(type)` return?","o":["object","type","class","NameError"],"a":1,"e":"In Python, classes are objects too, and the thing that creates classes is called a metaclass. The default metaclass is `type`.\n`type(5)` is int, `type(int)` is type, and `type(type)` is type itself: the chain ends there.","r":"type is the default metaclass and its own type.","g":["metaclass","class","object","instance","inheritance"],"cat":"py"},{"id":"PY-26","t":"m","l":2,"q":"In `try / except / else / finally`, when does `else` run?","o":["Always, right after the `try` block, whatever happens","Only when an exception was raised inside the `try` block","Only when no exception was raised inside the `try` block","Only after `finally` has finished running its code"],"a":2,"e":"`else` runs only if the `try` block finished without an exception.\nPut there the code that should run on success, but whose own errors you do NOT want the `except` above to catch.\n`finally` runs at the end in every case (success or error).","ec":"try:\n    data = load()\nexcept FileNotFoundError:\n    data = {}\nelse:\n    print(\"loaded\", len(data))   # only on success\nfinally:\n    print(\"done\")                # always","r":"try → except (error) / else (no error) → finally (always).","g":["try_except","exception","n_builtin_exc","context_manager","j_finally"],"fa":"Only if no exception was raised in `try`","cat":"py"},{"id":"PY-27","t":"m","l":3,"q":"What does this print?","c":"def f():\n    try:\n        return 1\n    finally:\n        return 2\n\nprint(f())","o":["1","2","1 then 2","SyntaxError"],"a":1,"e":"`finally` always runs, even after a `return` in `try`.\nIf `finally` also contains a `return`, that second return replaces the first one, so `f()` returns 2. It can even hide exceptions.\nThat is why a return inside finally is considered a bug; recent Python versions warn about it.","r":"Never return inside finally.","g":["try_except","function","scope","exception","j_finally"],"cat":"py"},{"id":"PY-28","t":"m","l":2,"q":"Which methods make an object an iterator?","o":["`__len__` and `__getitem__`, which allow indexing and length","`__iter__` and `__next__`, with `StopIteration` raised at the end","`__enter__` and `__exit__`, which handle setup and cleanup","`__call__` and `__next__`, which allow calling and advancing"],"a":1,"e":"An iterator is an object that gives you the next value each time you call `next()` on it.\nIt needs `__next__` (return the next value, or raise StopIteration when there are no more) and `__iter__` (return itself).\nA `for` loop calls these methods for you behind the scenes.","r":"Iterator = __iter__ + __next__.","g":["iterator","iterable","dunder","n_iter_next"],"fa":"`__iter__` and `__next__` (raising `StopIteration` at the end)","cat":"py"},{"id":"PY-29","t":"m","l":2,"q":"What does this print?","c":"def inner():\n    yield 1\n    yield 2\n\ndef outer():\n    yield 0\n    yield from inner()\n    yield 3\n\nprint(list(outer()))","o":["[0, <generator>, 3]","[0, 1, 2, 3]","[0, 3]","[0, [1, 2], 3]"],"a":1,"e":"`yield from inner()` passes along every value that `inner()` produces, as if `outer()` yielded them itself.\nSo we get 0, then 1 and 2 from inner, then 3.","r":"yield from = hand over to another generator.","g":["generator","lazy","iterator","function","n_yield"],"cat":"py"},{"id":"PY-30","t":"m","l":3,"q":"What is the main overhead of `multiprocessing.Pool.map` compared to threads?","o":["The GIL is shared between processes, so they block each other","Arguments and results must be pickled and sent between processes","Processes cannot use more than one CPU core at the same time","Pool.map cannot return results, so you must write to files"],"a":1,"e":"Processes do not share memory. To send work to another process, Python must turn the arguments into bytes (pickling), send them, and convert the results back.\nFor tiny tasks or very large data, this copying can take longer than the work itself.\nSend work in bigger chunks so the overhead is paid less often.","r":"Processes pay a cost to copy data (pickle) between them.","g":["process","pickle","n_multiprocessing","gil","thread","cpu_bound"],"cat":"py"},{"id":"PY-31","t":"m","l":2,"q":"What is the idiomatic use of `@classmethod`?","o":["Methods that need neither the class nor the instance","Alternative constructors, like `Date.from_iso('2026-01-01')`","Making a method private so only the class can call it","Overriding `__init__` to change how objects are created"],"a":1,"e":"A classmethod receives the class (`cls`) instead of an object.\nIts typical use is an alternative constructor: another way to build an object, for example from a string. Because it calls `cls(...)`, it also builds the right type when used on a subclass.\nA staticmethod receives nothing automatically; it is just a normal function kept inside the class.","ec":"class Date:\n    def __init__(self, y, m, d): ...\n\n    @classmethod\n    def from_iso(cls, text):\n        y, m, d = map(int, text.split(\"-\"))\n        return cls(y, m, d)","r":"classmethod = alternative constructor.","g":["class","instance","method","n_init"],"fa":"Alternative constructors such as `Date.from_iso(\"2026-01-01\")`","cat":"py"},{"id":"PY-32","t":"m","l":2,"q":"Building a large string with `s += piece` in a loop is discouraged because…","o":["Strings are mutable, so they can get corrupted in a loop","It can be quadratic, since each `+=` may copy the whole string","It raises a MemoryError once the string passes 1 MB","f-strings are required for any string longer than a line"],"a":1,"e":"Strings cannot be changed (they are immutable). So `s += piece` builds a brand-new string and copies all the old characters every time.\nWith many pieces this gets very slow (time grows with the square of the size).\nCollect the pieces in a list and join them once at the end.","ec":"parts = []\nfor row in rows:\n    parts.append(str(row))\ntext = \"\".join(parts)","r":"Build big strings with \"\".join(list).","g":["immutable","big_o","z_loop","object","z_data_type"],"fa":"It can be quadratic because each `+=` may copy the whole string","cat":"py"},{"id":"PY-33","t":"m","l":2,"q":"Which structure gives O(1) append and pop at both ends?","o":["list","collections.deque","tuple","heapq"],"a":1,"e":"A Python list is an array: inserting or removing at the FRONT shifts every other element, which is O(n).\n`collections.deque` (double-ended queue) is built for fast adds and removes at both ends: O(1).\nUse it for queues (first in, first out) and sliding windows.","r":"Need a queue in Python? Use collections.deque.","g":["deque","big_o","queue","sliding_window"],"cat":"py"},{"id":"PY-34","t":"m","l":3,"q":"What is the difference between `__new__` and `__init__`?","o":["They are aliases, so defining either one has the same effect","`__new__` creates and returns the instance; `__init__` fills it in","`__init__` runs first and `__new__` runs after it","`__new__` is only used when you write a metaclass"],"a":1,"e":"Creating an object happens in two steps: `__new__` builds the empty object and returns it, then `__init__` fills it with starting values.\nYou rarely need `__new__`. It is used when you must control creation itself: subclassing immutable types like int or str, or returning an existing (cached) object.","r":"__new__ creates, __init__ initializes.","g":["dunder","class","instance","n_init","immutable"],"fa":"`__new__` creates and returns the instance; `__init__` initializes it","cat":"py"},{"id":"PY-35","t":"m","l":2,"q":"What happens?","c":"x = 10\ndef f():\n    print(x)\n    x = 5\n\nf()","o":["Prints 10","Prints 5","UnboundLocalError","NameError: x is not defined"],"a":2,"e":"Python decides which names are local when it reads the whole function, before running it.\nBecause `x = 5` appears inside `f`, `x` is local for the ENTIRE function, even on the line before the assignment.\nSo `print(x)` tries to read a local `x` that has no value yet → UnboundLocalError. Use a different name, or `global x` if you really mean the outer one.","r":"Any assignment inside a function makes that name local everywhere in it.","g":["scope","function","z_variable","closure"],"cat":"py"},{"id":"PY-36","t":"m","l":2,"q":"You call a function decorated with `@functools.lru_cache` passing a `list`. What happens?","o":["The list is converted to a tuple","TypeError: unhashable type: 'list'","The cache is skipped silently","It works but never hits"],"a":1,"e":"`lru_cache` remembers results in a dictionary, using the arguments as the key.\nDictionary keys must be hashable (unchangeable). A list can change, so it is not hashable and you get a TypeError.\nPass a tuple instead of a list.","r":"Arguments of a cached function must be hashable.","g":["hash","memoization","n_lru_cache","immutable","mutable","function"],"cat":"py"},{"id":"PY-37","t":"m","l":1,"q":"What does this print?","c":"nums = [3, 1, 2]\nresult = nums.sort()\nprint(result)","o":["[1, 2, 3]","None","[3, 1, 2]","TypeError"],"a":1,"e":"`nums.sort()` sorts the list itself (in place) and returns None. That is a Python convention for methods that modify an object.\nSo `result` is None, while `nums` is now [1, 2, 3].\nIf you want a NEW sorted list and keep the original, use `sorted(nums)`.","r":"list.sort() → None. sorted(list) → new list.","g":["mutable","identity","z_variable","list","function"],"cat":"py"},{"id":"PY-38","t":"m","l":3,"q":"Several threads run `counter += 1` on a shared global, 1M times each. Is the final count guaranteed correct with the GIL?","o":["Yes, the GIL makes `counter += 1` a single atomic step","No, `+=` is several steps, and threads can interleave between them","Yes, but only on Linux, where the GIL is stricter","No, Python forbids sharing a global between threads"],"a":1,"e":"The GIL protects Python's internals, not your logic. `counter += 1` is several small steps: read counter, add 1, write it back.\nA thread can be paused between the read and the write. Meanwhile another thread updates the counter, and then the first thread writes an old value: one update is lost. This is a race condition.\nProtect shared data with a Lock.","ec":"lock = threading.Lock()\n\ndef work():\n    global counter\n    for _ in range(1_000_000):\n        with lock:\n            counter += 1","r":"The GIL is not thread safety. Use a Lock for shared data.","g":["race_condition","lock","thread","gil","j_bytecode"],"fa":"No, `+=` is a read-modify-write of several bytecodes and threads can interleave","cat":"py"},{"id":"PY-39","t":"m","l":1,"q":"Why is a bare `except:` considered harmful?","o":["It is a syntax error in Python 3, so the program will not run at all","It also catches `KeyboardInterrupt` and `SystemExit`, so Ctrl+C fails","It is much slower, because Python checks every type of exception","It only catches `ValueError`, so every other error passes through"],"a":1,"e":"A bare `except:` catches EVERYTHING, including Ctrl+C (`KeyboardInterrupt`) and `sys.exit()` (`SystemExit`). Your program may become impossible to stop, and real bugs are hidden.\nCatch only the errors you expect (for example `except ValueError:`), or at most `except Exception:` and log the error.","r":"Catch specific exceptions, never everything.","g":["exception","try_except","n_builtin_exc"],"fa":"It also catches `KeyboardInterrupt` and `SystemExit`, making programs hard to stop","cat":"py"},{"id":"PY-40","t":"m","l":3,"q":"What is the current state of the GIL in modern CPython (3.13+)?","o":["It was removed entirely in every build of CPython 3.13 and later","It is still the default; an optional free-threaded build (PEP 703) has none","It was replaced by asyncio as the main concurrency model","It only exists on Windows builds, not on Linux or on macOS"],"a":1,"e":"PEP 703 added an optional 'free-threaded' build of CPython (from 3.13) where the GIL is disabled, so threads can run Python code truly in parallel.\nThe normal Python most people install still has the GIL, and C libraries must be updated to work in the new mode.","r":"The GIL is still the default; free-threading is an optional build.","g":["gil","thread","cpu_bound","process","event_loop","concurrency"],"fa":"Still present in the default build; an optional free-threaded build (PEP 703) can run without it","cat":"py"},{"id":"PY-41","t":"f","l":2,"q":"Explain the GIL and how you would speed up a CPU-bound Python job.","a":"- GIL: a lock in CPython; only one thread executes Python code at a time. It protects reference counts and interpreter state.\n- It is released during blocking I/O and by many C extensions (NumPy, hashlib, zlib).\n- I/O-bound work: threads or `asyncio` work well.\n- CPU-bound options: `ProcessPoolExecutor` / `multiprocessing`; vectorize with NumPy/pandas; move the hot loop to Cython/Rust/C; free-threaded build (3.13+) where libraries support it.\n- Trade-offs: process start-up, pickling cost, memory duplication. Profile first (`cProfile`, `py-spy`).","g":["gil","thread","process","cpu_bound","io_bound","n_cpu","n_multiprocessing"],"cat":"py"},{"id":"PY-42","t":"f","l":2,"q":"How do decorators work? Write a decorator that logs how long a function takes.","a":"- Functions are objects: you can pass them around and return them.\n- `@deco` above `def f` means `f = deco(f)`.\n- The decorator returns a wrapper that runs code before/after calling the original.\n- Use `functools.wraps` to keep the original name and docstring.\n- With arguments you add a factory level: `@retry(3)` means `f = retry(3)(f)`.","ac":"import functools, time\n\ndef timed(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        start = time.perf_counter()\n        try:\n            return func(*args, **kwargs)\n        finally:\n            ms = (time.perf_counter() - start) * 1000\n            print(f\"{func.__name__} took {ms:.1f} ms\")\n    return wrapper","g":["decorator","higher_order","closure","n_wraps","j_finally"],"cat":"py"},{"id":"PY-43","t":"f","l":2,"q":"What is the difference between an iterable, an iterator and a generator?","a":"- Iterable: anything you can loop over; implements `__iter__` (list, dict, str, file).\n- Iterator: object with `__next__` that remembers its position and raises `StopIteration` at the end; `iter(iterable)` gives you one. Single pass.\n- Generator: an iterator created by a function with `yield` (or a generator expression). Its state pauses between yields; values are produced lazily.\n- Why it matters: streaming big files or DB rows with constant memory, pipelines, infinite sequences.","g":["iterable","iterator","generator","lazy","n_iter_next","n_yield"],"cat":"py"},{"id":"PY-44","t":"f","l":3,"q":"Explain how asyncio works and when you would choose it over threads or processes.","a":"- One thread, one event loop. Coroutines (`async def`) give control back at each `await`, so the loop can run other tasks while one waits on I/O.\n- Cooperative: any blocking call (CPU work, `time.sleep`, a sync DB driver) freezes everything.\n- Tools: `asyncio.gather`, `TaskGroup`, `create_task`, `Semaphore` to limit concurrency, `wait_for` for timeouts.\n- Choose asyncio for many simultaneous I/O operations (thousands of sockets, API fan-out, websockets).\n- Threads: simpler for a few blocking calls with sync libraries.\n- Processes: CPU-bound work.\n- Run blocking code from async with `asyncio.to_thread` / `run_in_executor`.","g":["event_loop","coroutine","async_await","blocking","n_cpu","n_to_thread","n_gather","n_sleep"],"cat":"py"},{"id":"PY-45","t":"m","l":1,"q":"What is the main difference between a list `[1, 2]` and a tuple `(1, 2)`?","o":["Lists can hold only numbers; tuples can hold any type","Lists can change after creation; tuples cannot be changed","Tuples cannot be indexed; lists can be indexed by position","There is no real difference; they are two names for one type"],"a":1,"e":"Both are ordered collections and you can read items by position (`x[0]`).\nA list can change after creation: append, remove or replace items. A tuple is fixed once created.\nUse tuples for fixed groups of values, like coordinates `(x, y)`. Because they cannot change, tuples can also be dictionary keys.","r":"List = changeable. Tuple = fixed.","g":["mutable","immutable","list"],"fa":"Lists are mutable (can change); tuples are immutable (cannot change after creation)","cat":"py"},{"id":"PY-46","t":"m","l":1,"q":"What does the last line print?","c":"def greet(name):\n    print(\"Hi\", name)\n\nresult = greet(\"Ana\")\nprint(result)","o":["Hi Ana","None","\"\"","An error"],"a":1,"e":"A function without a `return` statement returns `None` automatically.\n`greet` prints \"Hi Ana\" on the screen (that is a side effect), but the value it gives back is None. So `result` is None and the last line prints None.","r":"print() shows text; return gives a value back. No return → None.","g":["function","z_variable","scope","z_data_type","list"],"cat":"py"},{"id":"PY-47","t":"m","l":1,"q":"What is `\"python\"[-1]`?","o":["\"p\"","\"n\"","IndexError","\"o\""],"a":1,"e":"Positions (indexes) start at 0 from the left: \"p\" is 0, \"y\" is 1, and so on.\nNegative indexes count from the right: -1 is the last character, -2 the one before it.\nSo `\"python\"[-1]` is \"n\". This works the same for lists.","r":"Index 0 = first item, index -1 = last item.","g":["list","n_slicing","z_data_type","immutable","index"],"cat":"py"},{"id":"PY-48","t":"m","l":1,"q":"What is `nums[1:3]` if `nums = [10, 20, 30, 40, 50]`?","o":["[10, 20, 30]","[20, 30]","[20, 30, 40]","[10, 20]"],"a":1,"e":"A slice `[start:stop]` takes items from position `start` up to, but NOT including, `stop`.\nPosition 1 is 20, position 2 is 30, and position 3 (40) is excluded. Result: [20, 30].\nLeaving a side empty means 'from the beginning' or 'to the end': `nums[:2]` is [10, 20].","r":"Slices include start and exclude stop.","g":["list","n_slicing","index","z_data_type"],"cat":"py"},{"id":"PY-49","t":"m","l":1,"q":"What does this print?","c":"user = {\"name\": \"Ana\"}\nprint(user.get(\"age\"))","o":["KeyError","None","0","\"\""],"a":1,"e":"A dictionary stores key → value pairs. `user[\"age\"]` would raise KeyError because that key does not exist.\n`.get(\"age\")` is the safe way: it returns None when the key is missing. You can also choose a default: `user.get(\"age\", 0)` returns 0.","r":"dict.get(key, default) avoids KeyError.","g":["dict","z_data_type","exception","n_builtin_exc"],"cat":"py"},{"id":"PY-50","t":"m","l":1,"q":"What is `[x * 2 for x in range(4)]`?","o":["[2, 4, 6, 8]","[0, 2, 4, 6]","[0, 1, 2, 3]","[0, 2, 4, 6, 8]"],"a":1,"e":"`range(4)` gives 0, 1, 2, 3: four numbers, starting at 0 and stopping BEFORE 4.\nThe list comprehension multiplies each one by 2: [0, 2, 4, 6].\nIt is a short way to write a loop that builds a list.","ec":"result = []\nfor x in range(4):\n    result.append(x * 2)","r":"range(n) = 0 to n-1.","g":["list_comprehension","list","z_loop","iterable"],"cat":"py"},{"id":"PY-51","t":"m","l":1,"q":"What do `7 / 2` and `7 // 2` return in Python 3?","o":["3 and 3","3.5 and 3","3.5 and 3.5","3 and 3.5"],"a":1,"e":"`/` is normal division and always returns a float (a decimal number): 3.5.\n`//` is floor division: it divides and rounds DOWN to a whole number: 3.\n`%` gives the remainder: `7 % 2` is 1 (useful to check even/odd).","r":"/ → decimal, // → whole number, % → remainder.","g":["n_floor_div","z_data_type","z_variable"],"cat":"py"},{"id":"PY-52","t":"m","l":1,"q":"In a method `def area(self):`, what is `self`?","o":["A reserved keyword that refers to the class itself","The instance (object) the method was called on","The parent class that the current class inherits from","A global variable that every method can read"],"a":1,"e":"When you write `rect.area()`, Python actually calls `Rectangle.area(rect)`: the object before the dot is passed automatically as the first argument.\nBy convention that first parameter is called `self`. Through it, the method reads and changes that object's data, like `self.width`.","r":"self = the object the method is working on.","g":["instance","method","class","object"],"cat":"py"},{"id":"PY-53","t":"m","l":1,"q":"What is `__init__` for in a class?","o":["It deletes the object when the program does not need it any more","It runs when an object is created, to set its starting attributes","It runs only once, when the whole program starts up","It imports the modules that the class needs in order to work"],"a":1,"e":"Writing `Dog(\"Rex\")` creates a new Dog object and then automatically calls `__init__(self, \"Rex\")`.\nInside it you usually store the values on the object: `self.name = name`.\nThink of it as the setup step for every new object.","ec":"class Dog:\n    def __init__(self, name):\n        self.name = name\n\nrex = Dog(\"Rex\")\nprint(rex.name)   # Rex","r":"__init__ = setup that runs for every new object.","g":["class","instance","attribute","n_init","object"],"fa":"It runs automatically when a new object is created, to set its starting attributes","cat":"py"},{"id":"PY-54","t":"m","l":1,"q":"What is `len({1, 2, 2, 3, 3, 3})`?","o":["6","3","1","TypeError"],"a":1,"e":"A set keeps only unique values, so duplicates are dropped: {1, 2, 3}, which has length 3.\nSets are also very fast to check membership (`x in s`).\nCommon trick: `list(set(items))` removes duplicates (but does not keep the order).","r":"Set = unique values, fast lookups.","g":["set","hash","z_data_type","list"],"cat":"py"},{"id":"PY-55","t":"m","l":1,"q":"What does this print?","c":"def f(*args, **kwargs):\n    print(args, kwargs)\n\nf(1, 2, mode=\"fast\")","o":["[1, 2] {'mode': 'fast'}","(1, 2) {'mode': 'fast'}","(1, 2, 'fast') {}","An error"],"a":1,"e":"`*args` collects extra positional arguments (passed without names) into a tuple: (1, 2).\n`**kwargs` collects extra keyword arguments (passed as name=value) into a dict: {'mode': 'fast'}.\nThey let a function accept any number of arguments. Decorators use them to pass everything through.","r":"*args → tuple of positional args. **kwargs → dict of named args.","g":["positional_arg","keyword_arg","function","z_parameter","default_arg"],"cat":"py"},{"id":"PY-56","t":"m","l":1,"q":"Why is `with open(\"data.txt\") as f:` preferred over `f = open(\"data.txt\")`?","o":["It reads the file faster than a plain `open()` call does","The file closes by itself when the block ends, even after an error","It creates the file for you when it does not exist yet","It loads the whole file into memory in a single step"],"a":1,"e":"An open file uses operating-system resources and must be closed.\nWith `with`, Python closes the file for you as soon as the indented block ends, also if an exception happens in the middle.\nThis pattern is called a context manager; it is also used for locks and database connections.","r":"Use with for anything that must be closed or released.","g":["context_manager","n_enter_exit","scope","exception","z_database"],"fa":"The file is closed automatically when the block ends, even if an error happens","cat":"py"},{"id":"PY-57","t":"m","l":1,"q":"What does this print?","c":"items = []\nif items:\n    print(\"has items\")\nelse:\n    print(\"empty\")","o":["has items","empty","An error","None"],"a":1,"e":"In an `if`, Python treats some values as False ('falsy'): an empty list [], an empty string \"\", 0, None and an empty dict {}.\nEverything else is 'truthy'. So `if items:` is the short way to check that a list is not empty.","r":"Empty things, 0 and None are falsy.","g":["z_loop","list","function","z_variable"],"cat":"py"},{"id":"PY-58","t":"m","l":1,"q":"What is a virtual environment (`python -m venv .venv`) for?","o":["Running Python code inside the browser without installing it","An isolated set of packages per project, so versions do not conflict","A faster interpreter that compiles your code to machine code","A Docker container that holds the whole project and its OS"],"a":1,"e":"Project A may need Django 4 while project B needs Django 5. If both install into the same global Python, they clash.\nA virtual environment gives each project its own folder of packages. After activating it, `pip install` installs only there.\nList the versions in `requirements.txt` or `pyproject.toml` so others can recreate it.","r":"One virtual environment per project.","g":["venv","dependency","n_pyproject","z_library","z_pip"],"fa":"An isolated set of installed packages per project, so projects do not conflict on library versions","cat":"py"},{"id":"PY-59","t":"m","l":1,"q":"Which exception does `int(\"abc\")` raise?","o":["TypeError","ValueError","KeyError","SyntaxError"],"a":1,"e":"The type is correct (`int()` accepts strings), but this particular value cannot become a number → ValueError.\nTypeError is when the TYPE itself is wrong, for example `\"2\" + 2` (string plus int).\nKeyError is a missing dictionary key; SyntaxError is code Python cannot even read.","r":"Wrong value → ValueError. Wrong type → TypeError.","g":["exception","z_data_type","try_except","z_variable","n_builtin_exc"],"cat":"py"},{"id":"PY-60","t":"m","l":0,"q":"What is Python?","o":["A high-level, general-purpose language known for readable code","A database system used to store large amounts of data","A web browser engine used to render pages and run scripts","An operating system that runs on servers and laptops"],"a":0,"e":"Python is a programming language: a way to give instructions to a computer using readable text.\nIt is called high-level because it hides low-level details such as memory management, and general-purpose because it is used for many things: automation scripts, web servers (FastAPI, Django), data analysis, testing.\nThe Python documentation describes it as interpreted, interactive and object-oriented.","r":"Python = readable, general-purpose language.","g":["z_programming_language","z_interpreter","z_backend","z_server","object"],"fa":"A high-level, general-purpose programming language known for readable code, used for scripts, web backends, data and automation","cat":"py"},{"id":"PY-61","t":"m","l":0,"q":"What does it mean that Python is an 'interpreted' language?","o":["You must translate each file to machine code by hand first","You run the source file directly with `python app.py`, no build step","It only works on Windows, where the interpreter is installed","It cannot be used in production because it is too slow"],"a":1,"e":"The interpreter is the program `python`. You give it a file and it reads and runs your code.\nCompare with Java: you first compile the code to bytecode with `javac`, then run it with `java`.\nBehind the scenes Python also does some translation, but from your point of view you just run the file.","r":"Interpreted = run the source file directly with the interpreter.","g":["z_interpreter","z_compiler","z_java","j_bytecode","n_javac","d_view"],"fa":"You run your source file directly with the Python interpreter (`python app.py`), with no separate build step that you run yourself","cat":"py"},{"id":"PY-62","t":"m","l":0,"q":"What does `age = 30` do in Python?","o":["It compares age with 30 and prints True or False on screen","It creates a variable called age that refers to the value 30","It defines a function called age that always returns 30","It prints the number 30 on the screen and stores nothing"],"a":1,"e":"A variable is a name that points to a value, so you can use the value later.\nThe single `=` means assign (store), not compare. Comparing uses `==`.\nIn Python you do not declare the type. `age` simply refers to the integer 30, and later it could refer to something else.","r":"variable = value stores the value under a name.","g":["z_variable","n_assignment","z_data_type"],"fa":"Creates a variable named age that refers to the value 30","cat":"py"},{"id":"PY-63","t":"m","l":0,"q":"What type is `{\"name\": \"Ana\", \"age\": 30}` in Python?","o":["list: an ordered sequence of items","dict: a collection of key-value pairs","tuple: a fixed sequence of items","str: a piece of text"],"a":1,"e":"Basic Python types:\n- `int` and `float`: numbers, like 30 and 3.5.\n- `str`: text, like \"Ana\".\n- `bool`: True or False.\n- `list`: ordered items that can change, like [1, 2, 3].\n- `dict`: key-value pairs inside curly braces. You read a value by its key: `person[\"name\"]` gives \"Ana\".","r":"{} with key: value pairs = dict.","g":["dict","list","z_data_type","hash_table","json"],"fa":"dict (dictionary): key-value pairs","cat":"py"},{"id":"PY-64","t":"m","l":0,"q":"What does this function call print?","c":"def greet(name):\n    return \"Hi \" + name\n\nprint(greet(\"Ana\"))","o":["Hi Ana","greet","Hi name","Nothing at all"],"a":0,"e":"`def` defines a function: a named block of code that you can run whenever you want.\n`greet(\"Ana\")` calls it, giving \"Ana\" as the argument for the parameter `name`.\n`return` sends a value back to whoever called the function. `print` then shows that value.\nSo `\"Hi \" + \"Ana\"` gives `Hi Ana`.","r":"def defines a function. return gives back a value.","g":["function","z_parameter","z_variable","n_print_return","scope"],"cat":"py"},{"id":"PY-65","t":"m","l":0,"q":"How does Python know which lines belong inside an `if` or a loop?","o":["With curly braces { }, like in Java or JavaScript","With indentation: lines indented the same amount form one block","With semicolons at the end of every line in the block","With the words BEGIN and END around the block"],"a":1,"e":"Many languages (Java, JavaScript) use { } for blocks. Python uses indentation, so the layout is part of the grammar.\nThe line before an indented block ends with a colon `:`.\nIf you mix tabs and spaces or indent wrongly, Python raises an IndentationError.","ec":"if age >= 18:\n    print(\"adult\")      # inside the if\n    print(\"welcome\")    # also inside\nprint(\"done\")           # outside, always runs","r":"Python blocks = colon + indentation.","g":["z_indentation","javascript","z_java","z_loop"],"fa":"With indentation: the block is the group of lines indented the same amount (usually 4 spaces)","cat":"py"},{"id":"PY-66","t":"m","l":0,"q":"What does this loop print?","c":"for n in [1, 2, 3]:\n    print(n * 2)","o":["1 2 3 (one per line)","2, 4 and 6 (one per line)","6 (the sum, printed once)","[2, 4, 6] (printed as a list)"],"a":1,"e":"A `for` loop repeats a block once for each item of a collection.\nFirst n is 1 and it prints 1 * 2 = 2, then n is 2 and it prints 4, then n is 3 and it prints 6.\nEach `print` writes on its own line. It does not build a list; for that you would use a list comprehension.","r":"for item in collection: runs once per item.","g":["z_loop","list","n_print_return","iterable","list_comprehension"],"cat":"py"},{"id":"PY-67","t":"m","l":0,"q":"What does `import json` do?","o":["It downloads the json library from the internet every time","It makes the `json` module's code available in your file","It creates a new empty file called json in the folder","It deletes any variable that is named json"],"a":1,"e":"Python code is organized in modules (files) and packages (folders of modules).\n`import json` loads the standard-library module that reads and writes JSON, so you can write `json.loads(text)`.\nPackages that are not in the standard library, like `requests` or `fastapi`, must be installed first with pip.","r":"import = bring someone else's code into your file.","g":["z_module","json","z_library","n_json_loads","z_pip"],"fa":"Makes the code of the `json` module available in your file (here, the standard library's JSON tools)","cat":"py"},{"id":"PY-68","t":"m","l":0,"q":"What are pip and PyPI?","o":["pip installs Python packages; PyPI is the online repository they come from","pip is a text editor for Python files; PyPI is a kind of database","pip runs the tests of a project; PyPI deploys the application","pip is the Python interpreter; PyPI is the debugger that goes with it"],"a":0,"e":"pip is the tool you run to install, upgrade and remove packages. By default it downloads them from PyPI, the public index at pypi.org.\nExample: `python -m pip install requests`.\nA virtual environment (`python -m venv .venv`) keeps each project's packages separate, and `pip freeze > requirements.txt` records the list for others.","r":"pip installs. PyPI is where packages live.","g":["z_pip","venv","repository","index"],"fa":"pip installs Python packages; PyPI (Python Package Index) is the online repository where they come from","cat":"py"},{"id":"PY-69","t":"m","l":0,"q":"What is the difference between `print` and `return` in a function?","o":["They are the same: both show text and also end the function","`print` shows text on screen; `return` sends a value back to the caller","`return` shows text on screen; `print` ends the function now","`print` saves a value in a file; `return` clears the screen"],"a":1,"e":"A very common beginner confusion.\n`print(x)` only displays x for a human to read. The program cannot use it afterwards.\n`return x` hands x back to the caller: `total = add(2, 3)` stores 5 in `total`.\nIf a function only prints and does not return, `total` would be None.","r":"print = show. return = give back.","g":["function","n_print_return","z_variable","scope","z_parameter"],"fa":"`print` shows text on the screen; `return` sends a value back to the code that called the function so it can be used","cat":"py"},{"id":"JV-01","t":"m","l":1,"q":"What is the difference between the JDK, the JRE and the JVM?","o":["They are three names for the same Java installation","JVM runs bytecode; JRE adds libraries; JDK adds tools like `javac`","JDK runs programs; JRE compiles them; JVM stores the results","JVM is the compiler; JDK is the editor; JRE is the debugger"],"a":1,"e":"Java source code (`.java`) is first compiled into bytecode (`.class` files). Bytecode is not for your processor: it is for a program called the JVM (Java Virtual Machine), which reads it and runs it.\nThe JRE (Java Runtime Environment) is the JVM plus the standard class libraries, enough to RUN Java programs.\nThe JDK (Java Development Kit) is the JRE plus tools to BUILD programs: the compiler `javac`, `jar`, debuggers. As a developer you install the JDK.","r":"JDK = build + run. JRE = run. JVM = the engine that executes bytecode.","g":["j_jvm","j_jdk","j_bytecode","z_compiler","n_javac","z_java"],"fa":"JVM runs bytecode; JRE = JVM + standard libraries; JDK = JRE + developer tools such as the compiler (`javac`)","cat":"jv"},{"id":"JV-02","t":"m","l":1,"q":"\"Write once, run anywhere\" in Java is possible mainly because:","o":["Java code is translated to each OS's machine code on every edit","The compiler makes bytecode, and each OS has a JVM that runs it","Java programs only work on Windows, which hides the differences","Java has no operating system dependencies at all, so nothing is needed"],"a":1,"e":"`javac` compiles your code to bytecode, a neutral instruction set. The same `.class` or `.jar` file can be copied to Windows, Linux or macOS.\nEach platform has its own JVM that translates bytecode to what that computer understands.\nSo you compile once; the JVM handles the differences between machines.","r":"Bytecode is portable; the JVM is platform-specific.","g":["j_bytecode","j_jvm","z_java","n_os","z_compiler","n_class_file"],"fa":"The compiler produces bytecode, and each OS has its own JVM that can run the same bytecode","cat":"jv"},{"id":"JV-03","t":"m","l":1,"q":"Which statement about `int` and `Integer` is correct?","o":["They are the same type, written two different ways","`int` is a primitive and cannot be null; `Integer` is an object and can","`Integer` is always faster than `int` because it is an object","`int` can be a generic type argument, as in `List<int>`"],"a":1,"e":"Java has 8 primitive types (`int`, `long`, `double`, `boolean`, `char`, `byte`, `short`, `float`). They hold a plain value and can never be null.\nEach primitive has a wrapper class (`Integer`, `Long`, `Double`...) that is a real object. It can be null and can be used in collections and generics: `List<Integer>` works, `List<int>` does not.\nJava converts between them automatically (autoboxing/unboxing). Unboxing a null `Integer` throws NullPointerException.","r":"Primitive = raw value. Wrapper = object (can be null).","g":["j_primitive","j_boxing","z_java","object","j_generics"],"fa":"`int` is a primitive (cannot be null); `Integer` is an object wrapper (can be null)","cat":"jv"},{"id":"JV-04","t":"m","l":1,"q":"What does this print?","c":"String a = new String(\"hi\");\nString b = new String(\"hi\");\nSystem.out.println((a == b) + \" \" + a.equals(b));","o":["true true","true false","false true","false false"],"a":2,"e":"For objects, `==` compares references: are both variables pointing to the exact same object in memory? `new String(...)` always creates a new object, so `a == b` is false.\n`.equals()` compares the content. Both strings contain \"hi\", so it is true.\nRule: use `.equals()` to compare text and other objects; use `==` for primitives and for checking `null`.","r":"== compares references, equals() compares content.","g":["j_equals_hashcode","j_string_pool","object","z_variable"],"cat":"jv"},{"id":"JV-05","t":"m","l":1,"q":"Why should you avoid `s += x` for building a long string inside a big loop?","o":["It is a syntax error when used inside a loop body","Strings are immutable, so each `+=` copies the old text","It converts the string to lowercase on every pass","It only works with numbers, not with plain text"],"a":1,"e":"A `String` in Java can never change after creation (it is immutable). `s += x` really means: create a new String with the old text plus x, and throw the old one away.\nIn a loop with thousands of iterations that means thousands of copies, which is slow and creates garbage.\n`StringBuilder` keeps an internal buffer that grows, so you append without copying every time. Call `.toString()` at the end.","ec":"StringBuilder sb = new StringBuilder();\nfor (int i = 0; i < 1000; i++) {\n    sb.append(i).append(',');\n}\nString result = sb.toString();","r":"Many appends in a loop: use StringBuilder.","g":["j_stringbuilder","j_string_pool","immutable","z_loop","z_java"],"fa":"Strings are immutable, so each `+=` creates a brand new String, copying all previous characters","cat":"jv"},{"id":"JV-06","t":"m","l":1,"q":"What does the keyword `static` mean on a method or field?","o":["It cannot be changed after its first assignment","It belongs to the class, so no instance is needed","It is only visible inside the same source file","It runs automatically when the program starts up"],"a":1,"e":"Normal (instance) fields and methods belong to each object: every `new Person()` has its own `name`.\nA `static` member belongs to the class: there is only one copy, shared by all objects, and you call it as `ClassName.method()` without `new`. `Math.max(1, 2)` and `main` are static.\nCareful: static mutable fields are shared state, which is a classic source of bugs in multi-threaded programs.","r":"static = one copy per class, not per object.","g":["j_static","instance","object","class","mutable"],"fa":"It belongs to the class itself, not to any single object, and you can use it without creating an instance","cat":"jv"},{"id":"JV-07","t":"m","l":1,"q":"What does `final` do?","o":["Variable: assign once. Method: no override. Class: no extends","It deletes the object at the end of the method call","It makes a variable global, so every class can change it","It marks the last line that the program will ever run"],"a":0,"e":"`final` means \"cannot be changed or replaced\", and it applies differently:\n- final variable: assigned once. For an object, the reference cannot point elsewhere, but the object's inside can still change (a `final List` can still receive `add`).\n- final method: subclasses cannot override it.\n- final class: nobody can extend it (`String` is final).","r":"final = no reassign, no override, no extend.","g":["j_final","z_variable","object","class"],"fa":"On a variable: it can be assigned only once. On a method: it cannot be overridden. On a class: it cannot be extended","cat":"jv"},{"id":"JV-08","t":"m","l":1,"q":"Which access modifier is used when you write NO keyword in front of a field or method?","o":["`public`: visible to every class in the project","`private`: visible only inside the same class","Package-private: visible only to classes in the same package","`protected`: visible to subclasses and the same package"],"a":2,"e":"Java has four levels of visibility:\n- `public`: everyone.\n- `protected`: same package plus subclasses.\n- (no keyword) package-private: only classes in the same package.\n- `private`: only inside the same class.\nGood practice (encapsulation): make fields `private` and expose only what is needed through public methods.","r":"No keyword = package-private.","g":["j_access_modifier","encapsulation","z_java","class"],"cat":"jv"},{"id":"JV-09","t":"m","l":1,"q":"What is the main difference between an interface and an abstract class in Java?","o":["There is no real difference, as both define methods","A class implements many interfaces but extends one class","Interfaces can have instance fields; abstract classes cannot","Abstract classes cannot contain any method with code"],"a":1,"e":"An interface is a contract: a list of methods a class promises to provide (`implements`). A class can implement as many interfaces as it wants.\nAn abstract class is a half-built class that can have fields, constructors and some ready methods plus some `abstract` methods to complete. A class can `extend` only ONE class.\nSince Java 8 interfaces can also have `default` methods with code, but they still cannot keep per-object state.","r":"Many interfaces, one parent class. Only abstract classes carry state.","g":["interface","j_abstract_class","inheritance","z_java","class"],"fa":"A class can implement many interfaces but extend only one class; an abstract class can hold state (fields) and constructors","cat":"jv"},{"id":"JV-10","t":"m","l":1,"q":"Which collection should you choose to store unique items with no duplicates?","o":["`List`","`Set`","`Map` with duplicate keys","`Queue`"],"a":1,"e":"The Collections Framework gives you ready-made data structures:\n- `List`: ordered, allows duplicates, access by position (`ArrayList`).\n- `Set`: no duplicates (`HashSet`, `TreeSet`).\n- `Map`: key to value pairs, unique keys (`HashMap`).\n- `Queue` / `Deque`: items processed in order (`ArrayDeque`).\nAdding an existing item to a `Set` simply does nothing.","r":"List = ordered with duplicates. Set = unique. Map = key to value.","g":["j_collections","j_hashmap","z_data_structure","n_arraydeque","j_arraylist","n_hashset"],"cat":"jv"},{"id":"JV-11","t":"m","l":1,"q":"In practice, which is the better default for a general-purpose list: `ArrayList` or `LinkedList`?","o":["`LinkedList`, because it is always faster for every operation","`ArrayList`: fast index access and compact in memory","They behave exactly the same in speed and memory","`LinkedList`, because it is thread-safe and `ArrayList` is not"],"a":1,"e":"`ArrayList` stores items in a resizable array: `get(i)` is instant (O(1)), appending is fast, and items sit together in memory, which CPUs like.\n`LinkedList` stores each item in a separate node with links. Insertion in the middle is only cheap if you already hold the position; finding it takes O(n), and each node costs extra memory.\nUse `ArrayList` by default, and `ArrayDeque` when you need a queue or stack.","r":"Default to ArrayList.","g":["j_arraylist","linked_list","big_o","index","n_arraydeque","n_cpu"],"fa":"`ArrayList`: fast access by index and compact in memory; `LinkedList` is rarely better","cat":"jv"},{"id":"JV-12","t":"m","l":1,"q":"Which of these is a CHECKED exception?","o":["`NullPointerException`","`IllegalArgumentException`","`IOException`","`ArrayIndexOutOfBoundsException`"],"a":2,"e":"Checked exceptions extend `Exception` (but not `RuntimeException`). The compiler FORCES you to either catch them or declare them with `throws`. `IOException` (files, network) is the classic one.\nUnchecked exceptions extend `RuntimeException` (NullPointerException, IllegalArgumentException, IndexOutOfBounds...). They usually mean a bug in the code, and the compiler does not force you to handle them.\n`Error` (like OutOfMemoryError) is for serious JVM problems; you normally do not catch it.","r":"Checked = compiler forces you to handle. Unchecked = RuntimeException.","g":["j_checked_exc","j_runtime_exc","exception","z_compiler","n_jerrors","j_jvm"],"cat":"jv"},{"id":"JV-13","t":"m","l":1,"q":"What is the difference between method overloading and overriding?","o":["Overload: same name, new params. Override: subclass replaces","They are just two names for the very same feature","Overloading needs inheritance; overriding works in one class","Overriding changes the parameters; overloading the return type"],"a":0,"e":"Overloading: several methods with the same name but different parameter lists, e.g. `print(int)` and `print(String)`. The compiler picks the one that matches at compile time.\nOverriding: a subclass provides its own version of an inherited method with the same name and parameters, usually with `@Override`. The JVM chooses at runtime based on the real object type (polymorphism).","r":"Overload = same name, different params. Override = replace in a subclass.","g":["j_overload","j_override","polymorphism","n_override","class","z_compiler"],"fa":"Overloading: same name, different parameters in the same class. Overriding: a subclass replaces a parent's method with the same signature","cat":"jv"},{"id":"JV-14","t":"m","l":2,"q":"If you override `equals()` in a class, what else must you override, and why?","o":["`toString()`, so that the object prints in a readable way","`hashCode()`, since equal objects must have the same hash code","`clone()`, so that equal objects can also be copied","Nothing else, because `equals()` works on its own"],"a":1,"e":"The contract is: if `a.equals(b)` is true, then `a.hashCode() == b.hashCode()` must be true.\n`HashMap` and `HashSet` first use the hash code to choose a bucket (a storage slot), and only then call `equals` inside that bucket. If two equal objects have different hash codes, they land in different buckets and the map will not find one when you search with the other.\nCompute `hashCode` from the same fields you use in `equals` (`Objects.hash(a, b)`), or use a `record`.","r":"Override equals => override hashCode with the same fields.","g":["j_equals_hashcode","j_hashmap","hash","n_hashset"],"fa":"`hashCode()`, because equal objects must return the same hash code or HashMap/HashSet will misbehave","cat":"jv"},{"id":"JV-15","t":"m","l":2,"q":"What does this print?","c":"Integer a = 127, b = 127;\nInteger c = 128, d = 128;\nSystem.out.println((a == b) + \" \" + (c == d));","o":["true true","true false","false false","false true"],"a":1,"e":"When you write `Integer a = 127`, Java does autoboxing: it calls `Integer.valueOf(127)`. To save memory, `valueOf` keeps a cache of Integer objects for -128 to 127 and reuses them.\nSo 127 gives the same object both times (`==` true), but 128 creates two different objects (`==` false).\nLesson: never compare wrapper objects with `==`; use `.equals()`.","r":"Integer cache covers -128..127: compare wrappers with equals().","g":["j_boxing","j_equals_hashcode","j_primitive","j_string_pool"],"cat":"jv"},{"id":"JV-16","t":"m","l":2,"q":"What is `try-with-resources` for?","o":["Trying several resources in parallel until one works","Closing resources automatically, even after an error","Retrying an operation again and again until it succeeds","Allocating extra memory to the resource when needed"],"a":1,"e":"Resources such as files, database connections and sockets must be closed or they leak. The old way needed a `finally` block with extra try/catch.\nWith `try (Resource r = ...) { ... }`, Java calls `r.close()` automatically when the block ends, normally or by exception. The resource must implement `AutoCloseable`. Resources close in reverse order of creation.","ec":"try (BufferedReader br = new BufferedReader(new FileReader(\"data.txt\"))) {\n    System.out.println(br.readLine());\n}   // br.close() is called automatically","r":"Open it in the try parentheses and Java closes it for you.","g":["j_try_with_res","j_autocloseable","j_checked_exc","j_runtime_exc","exception","j_finally"],"fa":"Automatically closing resources (files, connections) at the end of the block, even if an exception happens","cat":"jv"},{"id":"JV-17","t":"m","l":2,"q":"What is type erasure in Java generics?","o":["Generics are erased at runtime, so `List<String>` is `List`","Generic types are erased from the source code after compiling","Java deletes any generic class that nobody uses anywhere","Generics make the program slower, as types are checked later"],"a":0,"e":"Generics (`List<String>`) let the compiler check types so you do not need casts. After checking, the compiler removes (erases) the type arguments and keeps only the raw type in the bytecode.\nConsequences: you cannot write `new T()`, `instanceof List<String>`, or create `new T[10]`, and `List<int>` is not allowed because type arguments must be objects.","r":"Generics are a compile-time check only.","g":["j_generics","j_type_erasure","generic","j_bytecode"],"fa":"Generic type information is removed by the compiler; at runtime a `List<String>` and a `List<Integer>` are both just `List`","cat":"jv"},{"id":"JV-18","t":"m","l":2,"q":"What does this print?","c":"List<String> names = List.of(\"Ana\", \"Bob\", \"Alicia\", \"Carl\");\nList<String> r = names.stream()\n    .filter(n -> n.startsWith(\"A\"))\n    .map(String::toUpperCase)\n    .toList();\nSystem.out.println(r);","o":["[Ana, Alicia]","[ANA, ALICIA]","[ANA, BOB, ALICIA, CARL]","[A, A]"],"a":1,"e":"A Stream is a pipeline for processing a collection: source, then intermediate steps, then a final (terminal) step.\n`filter` keeps names starting with \"A\" (Ana, Alicia). `map(String::toUpperCase)` converts each to upper case. `toList()` collects the result.\nThe original list is not modified. `n -> n.startsWith(\"A\")` is a lambda: a short anonymous function.","r":"Stream = source, intermediate ops (filter/map), terminal op (toList/collect).","g":["j_stream","j_lambda","lazy","j_optional","higher_order","j_collections"],"cat":"jv"},{"id":"JV-19","t":"m","l":2,"q":"What does this print?","c":"Stream.of(1, 2, 3)\n    .peek(x -> System.out.print(\"a\" + x + \" \"))\n    .map(x -> x * 2);\nSystem.out.println(\"done\");","o":["a1 a2 a3 done","done","done a1 a2 a3","Compile error"],"a":1,"e":"Streams are lazy: the intermediate operations (`peek`, `map`, `filter`) only describe what to do. Nothing runs until a terminal operation (`collect`, `forEach`, `count`, `toList`...) is called.\nHere there is no terminal operation, so the pipeline never runs and only \"done\" is printed.","r":"No terminal operation = nothing executes.","g":["j_stream","lazy","j_lambda","j_collections","iterator","higher_order"],"cat":"jv"},{"id":"JV-20","t":"m","l":2,"q":"What is the recommended way to use `Optional<T>`?","o":["Call `optional.get()` directly each time you need a value","Return type for 'maybe absent', with `orElse` or `map`","Use it for each field and each method parameter, always","Use it as a way to make a class thread-safe in Java"],"a":1,"e":"`Optional<T>` is a box that may or may not contain a value. It makes \"this can be missing\" visible in the method signature, instead of returning null and hoping callers remember to check.\nGood use: `repo.findById(id).map(User::getName).orElse(\"unknown\")` or `.orElseThrow()`.\nBad use: calling `.get()` without checking (it throws if empty), or using Optional for fields and parameters.","r":"Optional is for return values; avoid bare get().","g":["j_optional","z_null_java","j_lambda","j_stream","generic"],"fa":"Use it as a return type for \"might be absent\", and use `orElse`, `orElseThrow`, `map` instead of `get()` without checking","cat":"jv"},{"id":"JV-21","t":"m","l":2,"q":"What do records (Java 16+) give you with `record Point(int x, int y) {}`?","o":["A mutable class with setters for each component field","An immutable class with getters, `equals` and `toString`","A database table that is mapped from the components","A class that is not allowed to declare any methods"],"a":1,"e":"A record is a short way to declare a plain data carrier. The compiler generates the constructor, accessors (`p.x()`, not `getX()`), `equals`, `hashCode` and `toString` from the listed components.\nFields are final, so records are immutable. They are ideal for DTOs, API responses and map keys. Records can still have extra methods and validation in a compact constructor.","r":"record = immutable data class with boilerplate generated.","g":["j_record","j_immutable_class","immutable","j_equals_hashcode","api"],"fa":"An immutable data class with constructor, getters (`x()`), `equals`, `hashCode` and `toString` generated automatically","cat":"jv"},{"id":"JV-22","t":"m","l":2,"q":"Where do objects live in the JVM, and what lives on the stack?","o":["Objects on the stack; local primitives on the heap","Objects on the heap; each thread's stack holds locals and calls","Everything lives on the heap, including method calls","Everything lives on the stack, including all objects"],"a":1,"e":"The heap is the big shared memory area where all objects are created (`new`). The garbage collector cleans it.\nEach thread has its own stack: a small area where each method call gets a frame with its local variables (primitives and references to objects). When the method returns, the frame is removed automatically.\nA `StackOverflowError` means too many nested calls (usually infinite recursion); `OutOfMemoryError` means the heap is full.","r":"Heap = objects (shared). Stack = method frames (per thread).","g":["j_heap","j_stack_mem","j_gc","j_jvm","n_jerrors","recursion"],"fa":"Objects on the heap; each thread's stack holds local variables and method calls","cat":"jv"},{"id":"JV-23","t":"m","l":2,"q":"What does this print?","c":"static int f() {\n    try {\n        return 1;\n    } finally {\n        System.out.println(\"finally\");\n    }\n}\nSystem.out.println(f());","o":["1","finally, then 1","1, then finally","finally only"],"a":1,"e":"A `finally` block runs always, even if the `try` block executes `return`. Java first evaluates the return value (1), then runs `finally` (printing \"finally\"), then returns 1 to the caller.\nSo the output is `finally` on one line and `1` on the next.\nDo not put `return` inside `finally`: it would replace the original result and even hide exceptions.","r":"finally always runs, even after return.","g":["j_finally","exception","j_checked_exc","j_runtime_exc","try_except","j_static"],"cat":"jv"},{"id":"JV-24","t":"m","l":2,"q":"Why does this code throw `ConcurrentModificationException`?","c":"List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4));\nfor (Integer n : nums) {\n    if (n % 2 == 0) nums.remove(n);\n}","o":["`remove` is not allowed on lists created with `new ArrayList`","The list was modified while the for-each iterator was walking it","`Integer` objects cannot be removed from a list","Another thread is changing the list at the same time"],"a":1,"e":"The for-each loop uses an iterator behind the scenes. The iterator remembers how many modifications the list had when it started. If you add or remove through the list itself during the loop, the iterator notices the count changed and fails fast with this exception. It happens even with a single thread.\nSafe options: `nums.removeIf(n -> n % 2 == 0)`, use `iterator.remove()`, or build a new list with a stream.","ec":"nums.removeIf(n -> n % 2 == 0);","r":"Do not modify a collection while iterating it; use removeIf or Iterator.remove.","g":["j_cme","j_collections","iterator","j_hashmap","mutable","thread"],"fa":"Because the list was structurally modified while the for-each iterator was walking it","cat":"jv"},{"id":"JV-25","t":"m","l":2,"q":"Which is true about `HashMap`, `Hashtable` and `ConcurrentHashMap`?","o":["All three are equally safe and fast when many threads use them","`HashMap` is unsafe; `Hashtable` locks all; `ConcurrentHashMap` is finer","`HashMap` is the only one that allows null keys, and it is thread-safe","`ConcurrentHashMap` is always slower than `Hashtable` in every case"],"a":1,"e":"`HashMap` is fast but unsafe if several threads modify it at the same time (lost updates, even infinite loops in old versions).\n`Hashtable` is synchronized on every method, so only one thread works at a time. It is legacy; avoid it.\n`ConcurrentHashMap` is designed for concurrency: reads do not block and writes lock only small parts. It also offers atomic operations like `computeIfAbsent` and `merge`. It does not allow null keys or values.","r":"Shared map between threads: ConcurrentHashMap.","g":["j_hashmap","j_concurrenthashmap","race_condition","j_synchronized"],"fa":"`HashMap` is not thread-safe; `Hashtable` locks the whole map (old, slow); `ConcurrentHashMap` allows many threads with fine-grained locking","cat":"jv"},{"id":"JV-26","t":"m","l":2,"q":"What is the difference between `synchronized` and `volatile`?","o":["They are identical in effect, only the keyword is different","`synchronized` locks and shares writes; `volatile` only shares","`volatile` locks the whole object; `synchronized` does not lock","`volatile` can only be applied to methods and never to fields"],"a":1,"e":"`synchronized` makes a block run by one thread at a time (mutual exclusion) and also makes changes visible to the next thread that enters.\n`volatile` on a field only guarantees visibility: when one thread writes, others immediately see the new value (no stale cached copy). It does NOT make `count++` safe, because that is three steps: read, add, write.\nUse `volatile` for simple flags (`running = false`), `synchronized` or `AtomicInteger` for counters and compound actions.","r":"volatile = visibility only. synchronized = lock + visibility.","g":["j_synchronized","j_volatile","j_atomic","race_condition","lock","thread","j_thread_pool","j_concurrenthashmap"],"fa":"`synchronized` gives mutual exclusion plus visibility; `volatile` only guarantees that reads see the latest write (no atomicity for compound actions)","cat":"jv"},{"id":"JV-27","t":"m","l":2,"q":"Why use an `ExecutorService` (thread pool) instead of `new Thread()` for every task?","o":["Threads cannot be created with the `new` keyword at all","Threads are costly; a pool reuses a few and queues the rest","Executors make the code run on the GPU instead of the CPU","A pool guarantees that tasks never fail or throw exceptions"],"a":1,"e":"Each thread uses memory (around 1 MB of stack) and the OS needs time to create it. If a server started a new thread per request, a traffic spike could create thousands and crash.\nAn `ExecutorService` keeps a limited set of worker threads that take tasks from a queue and are reused. You submit tasks and get a `Future` for the result. Always shut it down (`shutdown()`) when finished.","ec":"ExecutorService pool = Executors.newFixedThreadPool(4);\nFuture<Integer> f = pool.submit(() -> 21 * 2);\nSystem.out.println(f.get());   // 42\npool.shutdown();","r":"Thread pool = reuse a bounded set of threads.","g":["j_thread_pool","j_executor","thread","n_os"],"fa":"Creating threads is expensive and unlimited threads can exhaust memory; a pool reuses a fixed number of threads and queues extra tasks","cat":"jv"},{"id":"JV-28","t":"m","l":2,"q":"When would you use `Comparator` instead of `Comparable`?","o":["`Comparable` is for sorting; `Comparator` is for hashing","`Comparable` is the natural order; `Comparator` is external","They are identical, only the name of the method changes","`Comparator` only works on numbers and never on objects"],"a":1,"e":"`Comparable<T>` is implemented by the class itself with `compareTo`. It defines ONE natural order (e.g. `String` alphabetical, `Integer` numeric).\n`Comparator<T>` is a separate object with `compare(a, b)`. You can have many: by name, by age, by date. It is also the only choice when you cannot modify the class.\nModern style: `people.sort(Comparator.comparing(Person::getAge).thenComparing(Person::getName))`.","r":"Comparable = natural order inside. Comparator = custom orders outside.","g":["j_comparable","j_comparator","j_collections","sorting","interface","j_lambda"],"fa":"`Comparable` defines the natural order inside the class; `Comparator` defines extra or external orderings without changing the class","cat":"jv"},{"id":"JV-29","t":"m","l":3,"q":"Java has a garbage collector. How can a Java program still have a memory leak?","o":["It cannot, because the GC always frees every object","By keeping references to objects it no longer needs","Only by calling `System.gc()` too many times in a row","Only by using primitives instead of objects everywhere"],"a":1,"e":"The GC frees objects that nothing can reach anymore. A leak in Java means objects are still reachable (something still points to them) but your program will never use them again.\nTypical causes: a static `Map` used as a cache with no size limit or expiry; listeners or callbacks registered and never removed; `ThreadLocal` values in pooled threads; unclosed resources.\nSymptoms: heap grows until `OutOfMemoryError`. Tools: heap dump + Eclipse MAT, VisualVM, JFR.","r":"Leak = still reachable but never used again.","g":["j_mem_leak","j_gc","j_heap","n_jerrors","callback"],"fa":"By keeping references to objects that are no longer needed, e.g. a static map/cache that only grows, forgotten listeners, or unclosed ThreadLocals","cat":"jv"},{"id":"JV-30","t":"m","l":3,"q":"What problem do virtual threads (Java 21) solve?","o":["They make CPU-heavy code run faster on more cores","Simple blocking code scaled to huge numbers of tasks","They replace the garbage collector with a cheaper one","They remove the need for synchronization in shared code"],"a":1,"e":"A normal (platform) thread maps 1:1 to an OS thread and is expensive, so a server can only have a few thousand. When a thread waits for I/O (database, HTTP), it just sits there wasting its slot.\nVirtual threads are lightweight threads managed by the JVM. When one blocks on I/O, the JVM parks it and runs another on the same OS thread. You can create millions.\nThey help with I/O-bound workloads (typical web services). They do NOT speed up CPU-bound work, and you still need to protect shared data.","ec":"try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {\n    ex.submit(() -> callSlowService());\n}","r":"Virtual threads = cheap blocking for I/O-heavy servers.","g":["j_virtual_thread","j_thread_pool","io_bound","j_jvm","n_os","n_cpu"],"fa":"They let you write simple blocking code while handling hundreds of thousands of concurrent tasks, because they are very cheap and the JVM, not the OS, schedules them","cat":"jv"},{"id":"JV-31","t":"m","l":3,"q":"Why is this counter NOT thread-safe even though the field is `volatile`?","c":"private volatile int count = 0;\n\nvoid increment() {\n    count++;\n}","o":["`volatile` only works on object references, not on `int` fields","`count++` is read, add, write: two threads can read the same value","An `int` field cannot be shared between threads","It is thread-safe, because `volatile` covers every operation"],"a":1,"e":"`volatile` guarantees that every thread sees the latest written value. But `count++` is not one step: (1) read count, (2) add 1, (3) write back.\nIf two threads both read 5, both write 6, and one increment is lost (a race condition).\nFixes: `AtomicInteger.incrementAndGet()` (lock-free and atomic), or make the method `synchronized`, or use `LongAdder` for very high contention.","ec":"private final AtomicInteger count = new AtomicInteger();\n\nvoid increment() {\n    count.incrementAndGet();\n}","r":"volatile does not make compound operations atomic.","g":["j_volatile","j_atomic","race_condition","j_final","j_synchronized","n_longadder"],"fa":"Because `count++` is read, add, write: two threads can read the same value and one update is lost","cat":"jv"},{"id":"JV-32","t":"m","l":3,"q":"What is the practical difference between `thenApply` and `thenCompose` in `CompletableFuture`?","o":["There is no difference at all, both are the same method","`thenApply` maps a result; `thenCompose` flattens futures","`thenCompose` blocks the thread; `thenApply` does not","`thenApply` handles the errors; `thenCompose` does not"],"a":1,"e":"A `CompletableFuture<T>` represents a result that will exist later, without blocking while you wait.\n`thenApply(f)`: when the result arrives, apply a plain function `T -> U` and get a `CompletableFuture<U>`.\n`thenCompose(f)`: use when `f` itself returns a `CompletableFuture<U>` (for example, another async call). Without it you would get a nested `CompletableFuture<CompletableFuture<U>>`.\nIt is the same idea as `map` vs `flatMap`.","ec":"CompletableFuture<Order> order =\n    findUserAsync(id)                       // CF<User>\n        .thenCompose(u -> findOrderAsync(u)) // CF<Order>\n        .thenApply(o -> o.withTax());","r":"thenApply = map. thenCompose = flatMap.","g":["j_completable_future","promise","async_await","j_thread_pool","j_executor"],"fa":"`thenApply` transforms the result with a normal function; `thenCompose` is for a function that itself returns a CompletableFuture and flattens it (like flatMap)","cat":"jv"},{"id":"JV-33","t":"m","l":3,"q":"How do you make a class truly immutable in Java?","o":["Mark only the class as `final`; nothing more is needed","`final` class, private final fields, no setters, copies","Add `volatile` to every one of the fields in the class","Make every field `static` so that all objects share it"],"a":1,"e":"An immutable object never changes after construction, so it is automatically thread-safe and can be shared and cached freely (`String` and `LocalDate` are immutable).\nRecipe: (1) `final` class so nobody subclasses and adds mutability, (2) `private final` fields, (3) no setters, (4) if a field is a mutable object (a `List`, a `Date`), copy it in the constructor and return a copy or an unmodifiable view in the getter.\nA `final List` field alone is not enough: the list contents could still change. Records do most of this for you (but still need defensive copies of mutable components).","ec":"public final class Team {\n    private final List<String> members;\n    public Team(List<String> m) { this.members = List.copyOf(m); }\n    public List<String> members() { return members; }  // already unmodifiable\n}","r":"final fields + no setters + defensive copies.","g":["j_immutable_class","j_defensive_copy","j_record","immutable","mutable","j_final"],"fa":"Make the class final, all fields `private final`, no setters, and defensively copy any mutable object that comes in or goes out","cat":"jv"},{"id":"JV-34","t":"m","l":3,"q":"A class overrides `equals` but NOT `hashCode`. What is the likely result?","c":"class P {\n    String n;\n    P(String n) { this.n = n; }\n    @Override public boolean equals(Object o) {\n        return o instanceof P p && p.n.equals(n);\n    }\n}\nSet<P> s = new HashSet<>();\ns.add(new P(\"a\"));\ns.add(new P(\"a\"));\nSystem.out.println(s.size());","o":["Always 1, because equal objects always share one slot","Likely 2: default hashCodes differ, so different buckets","Always 0, since the set rejects objects with no hashCode","A compile error, because `hashCode` is mandatory in Java"],"a":1,"e":"Without an override, `hashCode()` comes from `Object` and is based on the object's identity, so two different `P` objects almost always get different hash codes.\n`HashSet` uses the hash to pick a bucket. The two objects go to different buckets, so `equals` is never compared, and both are stored: size 2, even though `equals` says they are the same.\nThis breaks the contract. Fix: also override `hashCode` with `Objects.hash(n)`.","r":"Broken equals/hashCode contract = duplicates in hash collections.","g":["j_equals_hashcode","j_hashmap","n_override","n_hashset"],"fa":"Most likely 2: the default hashCode differs per object, so they land in different buckets and equals is never even called","cat":"jv"},{"id":"JV-35","t":"m","l":3,"q":"What does a \"stop-the-world\" pause in garbage collection mean, and how do modern collectors reduce it?","o":["The program is stopped forever and has to be restarted","All app threads pause during GC; G1 and ZGC shorten it","The GC stops the operating system for a short time","It only happens when `System.gc()` is called by hand"],"a":1,"e":"To safely move or free objects, the GC sometimes needs every application thread to pause. That pause is called stop-the-world. Long pauses make a service freeze (high latency spikes).\nG1 (default since Java 9) splits the heap into regions and collects the ones with most garbage first, aiming at a target pause time.\nZGC and Shenandoah do almost all work concurrently, with pauses of about a millisecond, even on very large heaps.\nTuning starts by measuring: GC logs (`-Xlog:gc`), not by guessing flags.","r":"Pause = threads frozen for GC. G1/ZGC aim for short pauses.","g":["j_stw","j_gc","j_heap","j_mem_leak","reference_counting","j_virtual_thread"],"fa":"All application threads are paused while the GC works; collectors like G1 and ZGC do most work concurrently or in small regions to keep pauses short","cat":"jv"},{"id":"JV-36","t":"f","l":1,"q":"Explain the four pillars of OOP with Java examples.","a":"- Encapsulation: hide data (`private` fields) and expose behavior through methods, so the class controls its own rules.\n- Inheritance: a class reuses and extends another (`class Dog extends Animal`). Prefer composition when it is not a true \"is-a\".\n- Polymorphism: the same call behaves differently depending on the real object: `Animal a = new Dog(); a.speak();` runs Dog's version.\n- Abstraction: expose what something does, hide how: interfaces and abstract classes (`List` vs `ArrayList`).\n- Interview tip: give one tiny example for each and say when inheritance is a bad idea.","g":["j_arraylist","z_java","z_oop","encapsulation","polymorphism"],"cat":"jv"},{"id":"JV-37","t":"f","l":2,"q":"Explain how a HashMap works internally.","a":"- It keeps an array of buckets. For `put(key, value)` it computes `key.hashCode()`, spreads the bits, and picks `index = hash % arraySize`.\n- If the bucket is empty, the entry is stored. If not (a collision), entries are chained in a linked list; since Java 8, a long chain (8+) becomes a balanced tree for faster search.\n- `get(key)`: find the bucket by hash, then use `equals` to find the exact key. That is why `equals` and `hashCode` must be consistent.\n- When the map is more than 75% full (load factor 0.75), the array doubles and entries are redistributed (rehash).\n- Average O(1) get and put, worst case O(log n). Not thread-safe; allows one null key.","g":["hash_table","collision","array","linked_list","tree","j_equals_hashcode","j_hashmap"],"cat":"jv"},{"id":"JV-38","t":"f","l":2,"q":"Explain the Java memory model: heap, stack, metaspace and garbage collection.","a":"- Heap: where all objects live; shared by all threads; divided into young generation (new objects, collected often and cheaply) and old generation (survivors, collected less often).\n- Stack: one per thread; holds method frames with local variables and references.\n- Metaspace: class definitions and metadata (outside the heap, grows with native memory).\n- GC: finds objects no longer reachable from roots (stack variables, static fields) and frees them. Common collectors: G1 (default), ZGC, Parallel.\n- Common errors: `OutOfMemoryError: Java heap space` (heap full or leak), `StackOverflowError` (deep or infinite recursion).","g":["n_jerrors","recursion","j_heap","n_g1_zgc","j_gc"],"cat":"jv"},{"id":"JV-39","t":"f","l":3,"q":"What concurrency tools does Java give you, and when do you use each?","a":"- `synchronized` / `ReentrantLock`: protect shared mutable state with mutual exclusion.\n- `volatile`: visibility of a simple flag.\n- `Atomic*` / `LongAdder`: lock-free counters.\n- `ConcurrentHashMap`, `CopyOnWriteArrayList`, `BlockingQueue`: thread-safe collections for shared data and producer/consumer.\n- `ExecutorService`: thread pools to run tasks; `CompletableFuture`: compose async steps.\n- Virtual threads (Java 21): simple blocking style for massive I/O concurrency.\n- Best rule: avoid shared mutable state; prefer immutable objects and message passing.","g":["mutable","j_concurrenthashmap","j_completable_future","j_executor","j_virtual_thread","j_synchronized","j_thread_pool","immutable"],"cat":"jv"},{"id":"JV-40","t":"f","l":2,"q":"What changed in modern Java (8 to 21) that every developer should know?","a":"- Java 8: lambdas, streams, `Optional`, `default` methods, `java.time` API.\n- Java 9 to 11: modules, `var` for local variables, `List.of`, HTTP client; Java 11 is an LTS (long-term support).\n- Java 14 to 17: records, switch expressions, text blocks, sealed classes, pattern matching for `instanceof`; Java 17 is an LTS.\n- Java 21 (LTS): virtual threads, record patterns, pattern matching for `switch`, sequenced collections.\n- Say: \"I mainly target the current LTS and use records, streams and `Optional` daily.\"","ac":"// Java 17+ examples\nrecord User(String name, int age) {}\n\nString text = \"\"\"\n    multi-line\n    text block\"\"\";\n\nObject o = 42;\nif (o instanceof Integer i && i > 40) { System.out.println(i); }\n\nString label = switch (day) {\n    case SATURDAY, SUNDAY -> \"weekend\";\n    default -> \"weekday\";\n};","g":["j_stream","j_record","j_lambda","j_optional","j_generics","j_virtual_thread","http","api"],"cat":"jv"},{"id":"JV-41","t":"m","l":0,"q":"What is Java?","o":["A general-purpose, object-oriented language for backends","A markup language used to describe the layout of web pages","A database engine used to store and query structured data","A web browser used to open sites and run page scripts"],"a":0,"e":"Java is a programming language. Programs are made of classes, and the same compiled program can run on Windows, Linux or macOS because it runs on the Java Virtual Machine.\nIt is very common in banks, large companies, backend services and Android history. Frameworks such as Spring Boot make it popular for web backends.\nJava is NOT JavaScript.","r":"Java = object-oriented language that runs on the JVM.","g":["z_java","j_jvm","z_backend","z_programming_language","vm","sp_spring_boot"],"fa":"A general-purpose, object-oriented programming language widely used for backend and enterprise software","cat":"jv"},{"id":"JV-42","t":"m","l":0,"q":"What happens between writing Java code and running it?","o":["`javac` makes `.class` bytecode; `java` runs it on the JVM","The browser reads the `.java` file and runs it directly","The code is converted into JavaScript and executed there","Nothing: the CPU runs the `.java` text exactly as written"],"a":0,"e":"The Java tutorial describes the steps:\n1. You write source code in plain text files ending in `.java`.\n2. The compiler `javac` turns them into `.class` files. They contain bytecode, the machine language of the Java Virtual Machine, not code for your CPU.\n3. The `java` tool runs your application with an instance of the JVM.\nMaven and your IDE do these steps for you, but this is what happens underneath.","ec":"javac Hello.java   # creates Hello.class (bytecode)\njava Hello         # JVM runs the bytecode","r":".java → javac → .class (bytecode) → JVM runs it.","g":["j_bytecode","j_jvm","z_compiler","z_java","n_class_file","n_javac"],"fa":"`javac` compiles the `.java` files into `.class` files of bytecode, then the `java` launcher runs them on the JVM","cat":"jv"},{"id":"JV-43","t":"m","l":0,"q":"What is the JVM (Java Virtual Machine)?","o":["A program that runs bytecode between your code and the OS","An editor that writes and checks the Java source code","A cloud server that hosts Java applications for you","A database that stores Java objects between the runs"],"a":0,"e":"Bytecode is not tied to a specific processor or operating system. Each operating system has its own JVM that knows how to run it.\nThis is the idea behind 'write once, run anywhere'.\nThe JVM also manages memory for you: it creates objects and the garbage collector removes the ones no longer used.","r":"JVM = the engine that runs Java bytecode on any OS.","g":["j_jvm","j_gc","z_java","j_bytecode","n_os","vm"],"fa":"A program that runs Java bytecode and sits between your program and the operating system, so the same `.class` files run on Windows, Linux or macOS","cat":"jv"},{"id":"JV-44","t":"m","l":0,"q":"What do you install to write, compile and run Java programs?","o":["A JDK (Java Development Kit)","Only a web browser with a Java plugin","Only Maven, which downloads the rest","Only a JavaScript runtime such as Node"],"a":0,"e":"The JDK includes the compiler (`javac`), the runtime with the JVM and other tools.\nOlder Java versions also had a JRE (Java Runtime Environment), a package with only what is needed to run programs. Since JDK 11 Oracle offers only the JDK, and smaller runtimes can be built with `jlink`.\nCommon JDK distributions: Oracle JDK, OpenJDK builds such as Eclipse Temurin.","r":"JDK = everything to develop and run Java.","g":["j_jdk","j_jvm","z_java","z_compiler","n_javac"],"cat":"jv"},{"id":"JV-45","t":"m","l":0,"q":"What does LTS mean for Java versions, and which versions are LTS?","o":["Long-Term Support: Java 8, 11, 17, 21 and 25","Latest Test Snapshot: every odd-numbered version","Language Translation System: Java versions 1 to 5","Legacy Tools Suite: only Java 8 and older versions"],"a":0,"e":"New Java versions come out regularly, but only some are Long-Term Support releases. Companies usually choose an LTS version for production.\nOracle's roadmap lists LTS releases: 8 (2014), 11 (2018), 17 (2021), 21 (2023) and 25 (September 2025). A new LTS is planned every two years.\nWhen a job says 'Java 17 or 21', it means these LTS versions.","r":"LTS: 8, 11, 17, 21, 25.","g":["z_lts","j_jdk","j_jvm","semver","j_virtual_thread","z_java"],"fa":"Long-Term Support: versions that get updates for years; Java 8, 11, 17, 21 and 25 are LTS releases","cat":"jv"},{"id":"JV-46","t":"m","l":0,"q":"In Java, what are a class and an object?","c":"Bicycle bike1 = new Bicycle();\nBicycle bike2 = new Bicycle();","o":["A class is a blueprint; an object is an instance made with `new`","A class is a variable; an object is a file on disk","An object is the blueprint; a class is one instance of it","They are the same thing under two different names"],"a":0,"e":"The Java tutorial: a class is the blueprint from which individual objects are created.\nHere `Bicycle` is the class. `bike1` and `bike2` are two separate objects (instances), each with its own data: one can be at gear 2 while the other is at gear 3.\n`new` creates a new object in memory.","r":"Class = blueprint. Object = instance made with new.","g":["class","object","z_oop","z_java","instance"],"fa":"A class is a blueprint; an object is one instance created from it with `new`","cat":"jv"},{"id":"JV-47","t":"m","l":0,"q":"In a Java class, what are fields and methods?","o":["Fields store the object's state; methods define its behavior","Fields are functions; methods are variables","Fields run the program; methods are only comments","They are the same thing, just named differently"],"a":0,"e":"The Java tutorial: an object stores its state in fields and exposes its behavior through methods.\nExample: for a `Bicycle`, the fields are `speed` and `gear`; the methods are `speedUp()` and `changeGear()`.\nMethods work on the object's fields. Keeping fields private and using methods to change them is called encapsulation.","r":"Fields = data. Methods = actions.","g":["z_field_method","encapsulation","z_java","object","class"],"fa":"Fields store the object's state (data); methods define its behavior (actions)","cat":"jv"},{"id":"JV-48","t":"m","l":0,"q":"What does this code do?","c":"int age = 30;\nString name = \"Ana\";","o":["Declares an int holding 30 and a String holding Ana","Compares age with 30 and stores the result in name","Creates two new classes that are called age and name","Imports two packages that are called age and name"],"a":0,"e":"Java is statically typed: every variable must have a declared type before you use it. `int` is a whole number, `String` is text, `double` a decimal number and `boolean` true or false.\nA semicolon `;` ends each statement. Text goes in double quotes.\nYou cannot put text into an int variable: the compiler rejects it, which catches mistakes before running.","r":"Java: declare the type, then the name, then the value.","g":["z_variable","z_data_type","j_primitive","n_assignment","z_java","z_compiler"],"fa":"Declares two variables with their types: an int (whole number) holding 30 and a String (text) holding Ana","cat":"jv"},{"id":"JV-49","t":"m","l":0,"q":"What is `public static void main(String[] args)`?","o":["The entry point: the method the JVM calls to start","A required import that every Java file must contain","A database command that starts a new connection","A comment style that is used to document a class"],"a":0,"e":"When you run `java Hello`, the JVM looks for a `main` method in that class and starts there.\n- public: callable from outside the class.\n- static: it belongs to the class, so no object is needed.\n- void: it returns nothing.\n- String[] args: the command-line arguments.\nIn Spring Boot, `main` is where `SpringApplication.run(...)` starts the app. JDK 25 also allows simpler forms such as `void main()` (JEP 512), but you will see the classic form almost everywhere.","r":"main = where a Java program starts.","g":["j_static","j_jvm","z_java","sp_spring_boot","class","j_jdk"],"fa":"The classic entry point: the method the JVM calls to start a Java program","cat":"jv"},{"id":"JV-50","t":"m","l":0,"q":"What are a package and an `import` in Java?","o":["A package groups classes; `import` allows short class names","A package is a delivery box; `import` deletes a class","A package is a database table; `import` creates one","Both are comment styles that are used to document code"],"a":0,"e":"The Java tutorial: a package is a namespace that organizes a set of related classes and interfaces, like folders on a computer.\nExample: `java.util.List` is the class `List` in the package `java.util`. After `import java.util.List;` you can write just `List`.\nYour own code is organized in packages too, usually named after the company domain reversed, like `com.mycompany.shop`.","r":"Package = folder-like namespace. import = use a class from it.","g":["z_package","z_java","class","interface"],"fa":"A package is a namespace that groups related classes; `import` lets you use a class from another package by its short name","cat":"jv"},{"id":"JV-51","t":"m","l":0,"q":"What is a JAR file?","o":["A ZIP-based file that bundles classes and resources","A code editor that is installed together with the JDK","A type of exception thrown when a class is missing","A Maven command that cleans the whole project folder"],"a":0,"e":"After compiling, you have many `.class` files. A JAR packs them into one file.\nLibraries are distributed as JARs (for example Jackson or JUnit). A Spring Boot application is usually built as an executable JAR that you start with `java -jar app.jar`.\nWith Maven, `mvn package` puts the JAR in the `target` folder.","r":"JAR = a zip of compiled Java code.","g":["z_jar","v_maven","z_java","z_library","sp_spring_boot","n_mvn_cmds"],"fa":"A Java ARchive: a ZIP-based file that bundles compiled classes and resources so a library or application can be shipped as one file","cat":"jv"},{"id":"JV-52","t":"m","l":0,"q":"What is a Java interface?","o":["A contract: method signatures that a class promises to implement","A visual screen that users see in the application","A database connection that a class opens and closes","A kind of loop that repeats until a condition is false"],"a":0,"e":"The Java tutorial: interfaces form a contract between the class and the outside world, enforced at build time by the compiler.\nIf a class says it implements an interface, all its methods must exist or the code will not compile.\nExample: `interface Payment { void pay(int amount); }` can be implemented by `CardPayment` and `PayPalPayment`. Callers only need to know the interface.","r":"Interface = a contract that classes implement.","g":["interface","abstraction","z_compiler","z_java","class"],"fa":"A contract: a group of method signatures that a class promises to implement; the compiler checks that it does","cat":"jv"},{"id":"JV-53","t":"m","l":0,"q":"What does `null` mean in Java, and what is a NullPointerException?","o":["`null` means no object is referenced; using it throws NullPointerException","`null` equals zero; the exception appears when dividing by zero","`null` is an empty string; the exception happens on empty strings","`null` is a keyword that marks the end of a loop"],"a":0,"e":"A variable that holds an object really holds a reference (an address). `null` means 'no object'.\n`String s = null; s.length();` crashes with NullPointerException (NPE), because there is no object to ask for its length.\nTypical fixes: check for null, initialize variables, or use `Optional` to make 'maybe nothing' explicit.","r":"null = no object. Using it as an object → NPE.","g":["z_null_java","j_optional","z_java","object","z_variable","n_null_compare"],"fa":"`null` means a reference points to no object; calling a method on it throws a NullPointerException","cat":"jv"},{"id":"JV-54","t":"m","l":0,"q":"What is an IDE?","o":["Integrated Development Environment: an editor plus tools","A type of server that hosts and runs web applications","A programming language that is used to write compilers","A cloud service that builds and deploys the projects"],"a":0,"e":"You can write code in any text editor, but an IDE saves a lot of time: it highlights errors as you type, suggests code, refactors safely, runs tests and lets you pause the program in a debugger.\nIntelliJ IDEA and Eclipse are common for Java; PyCharm for Python. Editors such as VS Code become IDE-like with extensions.","r":"IDE = editor + debugger + tools in one app.","g":["z_ide","j_jdk","z_compiler","z_terminal","z_framework","z_java"],"fa":"Integrated Development Environment: an editor with extra tools such as autocomplete, a debugger and run/test buttons, for example IntelliJ IDEA, Eclipse or PyCharm","cat":"jv"},{"id":"SPR-01","t":"m","l":1,"q":"What is Spring Framework, in one sentence?","o":["A CSS library used to style web pages and components","A Java framework whose container creates beans and wires them together","A database engine that stores and queries relational data","A build tool that compiles and packages Java projects"],"a":1,"e":"Spring is a very large Java framework. Its heart is the \"IoC container\" (Inversion of Control): instead of your code doing `new` and wiring everything by hand, Spring creates the objects, called beans, and gives each class the other objects it needs.\nOn top of that core it offers modules for web (Spring MVC), database access (Spring Data), security (Spring Security), transactions, testing and more.","r":"Spring = container that builds and wires your objects.","g":["sp_spring","sp_ioc","sp_bean","z_java","dependency_injection","sp_security"],"fa":"A Java framework whose core idea is a container that creates your objects (beans) and connects them to each other (dependency injection)","cat":"spr"},{"id":"SPR-02","t":"m","l":1,"q":"What does Spring Boot add on top of Spring?","o":["It replaces Java with a simpler language","It adds auto-configuration, starters and an embedded server","It adds a graphical interface for designing Spring apps","It introduces a new programming language for Spring"],"a":1,"e":"Plain Spring needs a lot of manual configuration (XML or Java config, choosing library versions, deploying a WAR to a separate server).\nSpring Boot makes sensible default choices:\n- Starters: one dependency (`spring-boot-starter-web`) brings a compatible set of libraries.\n- Auto-configuration: if it sees a library on the classpath, it configures it for you.\n- Embedded server (Tomcat by default): the app is a normal JAR you start with `java -jar`.\n- Actuator: health and metrics endpoints.","r":"Spring Boot = Spring with defaults, starters and an embedded server.","g":["sp_spring_boot","sp_starter","sp_autoconfig","z_java","z_server","n_javac"],"fa":"Auto-configuration, starter dependencies and an embedded server, so you can run a production-ready app with minimal setup","cat":"spr"},{"id":"SPR-03","t":"m","l":1,"q":"What is Dependency Injection (DI)?","o":["A class builds every object that it needs with `new`","A class declares needs and a container provides them","Copying a database table into a different schema","A technique to inject JavaScript code into web pages"],"a":1,"e":"Without DI, `OrderService` would write `new PaymentGateway()` inside itself, so it is tied to that exact class and hard to test.\nWith DI, `OrderService` receives a `PaymentGateway` (usually an interface) through its constructor. Spring decides which implementation to give.\nBenefits: loose coupling, easy replacement, and in unit tests you can pass a fake or mock.","ec":"@Service\npublic class OrderService {\n    private final PaymentGateway gateway;\n\n    public OrderService(PaymentGateway gateway) {   // injected by Spring\n        this.gateway = gateway;\n    }\n}","r":"Don't create your dependencies; receive them.","g":["dependency_injection","sp_ioc","sp_bean","j_final","dependency","unit_test"],"fa":"A class declares what it needs and an external container provides those objects, usually through the constructor","cat":"spr"},{"id":"SPR-04","t":"m","l":1,"q":"Which injection style is generally recommended in Spring?","o":["Field injection with `@Autowired` on fields","Constructor injection with final fields","Setter injection on every optional bean","Static fields that are set by the container"],"a":1,"e":"Constructor injection is preferred because:\n- Dependencies can be `final`, so the object is always fully built.\n- It is obvious what a class needs (look at the constructor).\n- Unit tests can create the class with `new` and pass mocks, without Spring.\n- Circular dependencies show up immediately.\nField injection hides dependencies and needs reflection or Spring to test. With a single constructor you do not even need `@Autowired`.","r":"Prefer constructor injection.","g":["sp_constructor_injection","dependency_injection","j_final","n_autowired","unit_test"],"fa":"Constructor injection","cat":"spr"},{"id":"SPR-05","t":"m","l":1,"q":"What do `@Component`, `@Service`, `@Repository` and `@RestController` have in common?","o":["They are all annotations used only inside test classes","Stereotypes: Spring detects them and registers beans","They only work when placed on interfaces, not on classes","They create the matching database tables at startup"],"a":1,"e":"`@Component` is the generic marker: \"Spring, please manage this class\" (component scanning finds it).\n`@Service` marks business logic, `@Repository` marks data access (it also translates persistence exceptions into Spring's exceptions), and `@RestController` marks a web controller that returns data (JSON) instead of views.\nThey behave like `@Component`, but names communicate the architecture.","r":"Stereotypes = \"manage this class as a bean\" + layer meaning.","g":["sp_stereotype","sp_bean","sp_component_scan","sp_rest_controller","z_annotation","z_persistence"],"fa":"They are stereotype annotations that tell Spring to detect the class and register it as a bean; the last three add meaning to a layer","cat":"spr"},{"id":"SPR-06","t":"m","l":1,"q":"What is the default scope of a Spring bean?","o":["Prototype: a new instance on every injection","Singleton: one shared instance per application context","Request: one instance for each HTTP request","Session: one instance for each logged-in user"],"a":1,"e":"By default Spring creates ONE instance of each bean and shares it everywhere (singleton scope; not the GoF pattern, but one per container).\nBecause many threads use the same object, singleton beans should be stateless: avoid mutable fields that change per request.\nOther scopes exist (`prototype`, `request`, `session`) but are rarely needed.","r":"Beans are singletons by default, so keep them stateless.","g":["sp_bean_scope","sp_bean","singleton","stateless","instance","mutable"],"cat":"spr"},{"id":"SPR-07","t":"m","l":1,"q":"What is the purpose of `@SpringBootApplication`?","o":["It starts the database that the application will use","It combines configuration, auto-config and component scan","It defines a REST endpoint directly on the main class","It runs the unit tests when the application starts"],"a":1,"e":"Placed on your main class, it is a shortcut for three annotations:\n- `@Configuration`: the class can define beans.\n- `@EnableAutoConfiguration`: turn on Spring Boot's automatic setup.\n- `@ComponentScan`: scan this package and sub-packages for `@Component`, `@Service`...\nThat is why the main class should live in the top-level package of your project.","ec":"@SpringBootApplication\npublic class App {\n    public static void main(String[] args) {\n        SpringApplication.run(App.class, args);\n    }\n}","r":"Main class annotation = config + auto-config + component scan.","g":["sp_autoconfig","sp_component_scan","sp_configuration","z_annotation","j_static","sp_spring_boot"],"fa":"It combines `@Configuration`, `@EnableAutoConfiguration` and `@ComponentScan`, marking the main class of the app","cat":"spr"},{"id":"SPR-08","t":"m","l":1,"q":"What does this endpoint do?","c":"@RestController\n@RequestMapping(\"/api/users\")\npublic class UserController {\n\n    @GetMapping(\"/{id}\")\n    public User get(@PathVariable Long id) {\n        return userService.findById(id);\n    }\n}","o":["Answers `GET /api/users/42` with the user as JSON","Answers `POST /api/users` and creates a new user","Reads `id` from the JSON body of the request","Deletes the user that has the id in the path"],"a":0,"e":"`@RestController` means every method returns data written directly to the HTTP response body (Spring converts the object to JSON with Jackson).\n`@RequestMapping(\"/api/users\")` gives the base path, `@GetMapping(\"/{id}\")` handles GET requests, and `@PathVariable` takes the value from the URL.\nSo `GET /api/users/42` calls `get(42)`.","r":"@PathVariable = from the URL path. @RequestParam = from ?query. @RequestBody = from the body.","g":["sp_rest_controller","sp_path_variable","json","http_method","z_url","sp_request_body"],"fa":"Responds to `GET /api/users/42` with the user serialized as JSON, where `id` = 42","cat":"spr"},{"id":"SPR-09","t":"m","l":1,"q":"Which annotation reads a JSON request body into a Java object?","o":["`@PathVariable`","`@RequestParam`","`@RequestBody`","`@ResponseBody`"],"a":2,"e":"`@RequestBody` tells Spring to read the HTTP body (usually JSON) and convert it into the Java parameter with Jackson.\n`@RequestParam` reads query parameters (`/search?name=ana`), `@PathVariable` reads parts of the path.\n`@ResponseBody` is the opposite direction (object to body); `@RestController` already applies it to all methods.","ec":"@PostMapping\npublic ResponseEntity<User> create(@Valid @RequestBody CreateUserRequest req) {\n    User created = userService.create(req);\n    return ResponseEntity.status(HttpStatus.CREATED).body(created);   // 201\n}","r":"Body = @RequestBody. Query = @RequestParam. Path = @PathVariable.","g":["sp_request_body","json","z_java","sp_path_variable","z_annotation","query_param"],"cat":"spr"},{"id":"SPR-10","t":"m","l":2,"q":"Where do you usually put settings such as the database URL in Spring Boot, and how do you switch between environments?","o":["Hard-coded in the Java classes, changed by recompiling","In `application.yml`, with `spring.profiles.active`","Only in `pom.xml`, inside the dependencies section","In the browser, sent along with each user request"],"a":1,"e":"Spring Boot reads configuration from `application.properties` or `application.yml` in `src/main/resources`.\nFor different environments you create profile files like `application-dev.yml` and `application-prod.yml` and activate one with `spring.profiles.active=prod` (or the `SPRING_PROFILES_ACTIVE` environment variable).\nSecrets (passwords, API keys) should not be committed: override them with environment variables or a secrets manager.","ec":"spring:\n  datasource:\n    url: jdbc:postgresql://localhost:5432/app\n    username: app\n    password: ${DB_PASSWORD}   # from an environment variable","r":"Config in application.yml, per-environment via profiles, secrets via env vars.","g":["sp_profile","sp_config_props","env_var","n_app_props","sp_spring_boot","n_maven_layout"],"fa":"In `application.properties` or `application.yml`, with profiles (`application-dev.yml`, `application-prod.yml`) activated by `spring.profiles.active`","cat":"spr"},{"id":"SPR-11","t":"m","l":2,"q":"What does Spring Boot auto-configuration do?","o":["It rewrites your code automatically while compiling","It reads the classpath and registers default beans","It downloads any missing libraries while running","It formats your code to match the Spring style"],"a":1,"e":"Auto-configuration classes are conditional: \"if class X is on the classpath and no bean of type Y exists, create Y\".\nExample: add `spring-boot-starter-data-jpa` and a PostgreSQL driver, set the URL in properties, and Spring Boot creates the `DataSource`, `EntityManagerFactory` and transaction manager for you.\nIf you define your own bean of that type, the auto-configured one backs off. To see what happened, run with `--debug`.","r":"Auto-config = conditional defaults that back off when you provide your own.","g":["sp_autoconfig","sp_starter","sp_spring_boot","sp_jdbc","transaction"],"fa":"It inspects the classpath and your properties and registers sensible beans automatically (e.g. a DataSource if a JDBC driver is present), backing off if you define your own","cat":"spr"},{"id":"SPR-12","t":"m","l":2,"q":"What is the difference between `@Component` and `@Bean`?","o":["There is no difference; both register a bean the same way","`@Component` scans your class; `@Bean` uses a method result","`@Bean` is meant for tests only, not for production code","`@Component` can only be placed on interfaces, not classes"],"a":1,"e":"`@Component` (and its stereotypes) annotates your own class, and Spring discovers it by component scanning.\n`@Bean` is placed on a method in a `@Configuration` class. The returned object is registered as a bean. Use it when you cannot annotate the class (a library class like `ObjectMapper` or `RestClient`) or when construction needs custom logic.","ec":"@Configuration\npublic class AppConfig {\n    @Bean\n    public Clock clock() {\n        return Clock.systemUTC();\n    }\n}","r":"@Component = my class. @Bean = a factory method for any class.","g":["sp_bean","sp_configuration","sp_ioc","sp_bean_scope","sp_component_scan","sp_autoconfig"],"fa":"`@Component` goes on a class you own and is found by scanning; `@Bean` goes on a method inside a `@Configuration` class and registers the returned object, useful for third-party classes","cat":"spr"},{"id":"SPR-13","t":"m","l":2,"q":"What happens if two beans of the same type exist and you inject that type without more information?","o":["Spring picks one of the beans at random for you","Startup fails (NoUniqueBeanDefinition); use `@Primary`","Spring injects both of the beans into the same field","Nothing fails, and the field is injected as null"],"a":1,"e":"If `PaymentGateway` has two implementations (`StripeGateway`, `PaypalGateway`), Spring cannot know which one you want and fails at startup (good: you find out immediately).\nFixes: mark one as `@Primary` (default choice), use `@Qualifier(\"stripeGateway\")` at the injection point, or inject `List<PaymentGateway>` / `Map<String, PaymentGateway>` if you want all of them.","r":"Ambiguity => @Primary or @Qualifier.","g":["sp_bean","dependency_injection","sp_ioc","sp_constructor_injection","sp_stereotype","sp_spring"],"fa":"Startup fails with NoUniqueBeanDefinitionException; resolve it with `@Primary` or `@Qualifier`","cat":"spr"},{"id":"SPR-14","t":"m","l":2,"q":"What does `@Transactional` do?","o":["It makes the method run faster by caching the results","It wraps the method in a transaction: commit or rollback","It makes the method run asynchronously in another thread","It encrypts the data that the method reads and writes"],"a":1,"e":"A transaction groups several database operations so they all succeed or all fail (ACID). `@Transactional` does this declaratively: Spring starts a transaction before the method and commits after it.\nDefault rollback rule: only for unchecked exceptions (RuntimeException, Error). A checked exception does NOT roll back unless you write `@Transactional(rollbackFor = Exception.class)`.\nPlace it on service methods (the unit of work), not on controllers or repositories.","ec":"@Transactional\npublic void transfer(Long from, Long to, BigDecimal amount) {\n    accounts.withdraw(from, amount);\n    accounts.deposit(to, amount);   // if this throws, the withdraw is undone\n}","r":"@Transactional: commit on success, rollback on RuntimeException by default.","g":["sp_transactional","transaction","acid","rollback","j_checked_exc","n_class_file"],"fa":"Wraps the method in a database transaction: commit if it completes, roll back if a RuntimeException (or Error) escapes","cat":"spr"},{"id":"SPR-15","t":"m","l":3,"q":"Why might `@Transactional` NOT work in this code?","c":"@Service\npublic class ReportService {\n\n    public void generate() {\n        saveAll();               // call inside the same class\n    }\n\n    @Transactional\n    public void saveAll() { ... }\n}","o":["Because the method is public and it must be private","Transactions use a proxy; a call within the class skips it","Because `@Transactional` only ever works on interfaces","Because the method has no parameters declared in it"],"a":1,"e":"Spring does not change your class. It wraps the bean in a proxy object that starts and commits the transaction around the call.\nWhen an outside class calls `reportService.saveAll()`, it goes through the proxy and works. But when `generate()` calls `saveAll()` inside the same object, it is a normal Java call on `this`, so the proxy is skipped and there is no transaction.\nSame problem with `private` or `final` methods. Fix: move the method to another bean, or put `@Transactional` on the method called from outside.","r":"Self-invocation and private methods bypass Spring's proxy.","g":["sp_proxy","sp_transactional","sp_aop","transaction","j_final","sp_stereotype"],"fa":"Because Spring applies transactions through a proxy, and a call from another method of the same class (self-invocation) bypasses the proxy","cat":"spr"},{"id":"SPR-16","t":"m","l":2,"q":"What does a Spring Data JPA repository interface give you?","c":"public interface UserRepository extends JpaRepository<User, Long> {\n    Optional<User> findByEmail(String email);\n}","o":["Nothing until you write the SQL for every single method","Ready-made CRUD methods and queries from method names","Only read operations, with no way of saving any data","A web page to browse the data stored in the database"],"a":1,"e":"You only declare an interface. At startup Spring Data creates the implementation for you.\n`JpaRepository<User, Long>` gives CRUD methods, paging and sorting. Method names like `findByEmail` or `findByAgeGreaterThanAndActiveTrue` are parsed and turned into queries automatically (derived queries).\nFor complicated queries, use `@Query(\"select ...\")` with JPQL or native SQL.","r":"Declare the interface; Spring writes the implementation.","g":["sp_data_jpa","sp_jpa","orm","n_jparepo","sql"],"fa":"Ready-made CRUD methods (`save`, `findById`, `findAll`, `deleteById`) plus queries generated from method names such as `findByEmail`","cat":"spr"},{"id":"SPR-17","t":"m","l":2,"q":"In JPA, what do `@Entity` and `@Id` mean?","o":["`@Entity` marks a class mapped to a table; `@Id` marks the primary key","`@Entity` is a REST controller; `@Id` is a URL parameter","`@Entity` creates a bean; `@Id` is the id of a thread","Both only change how the class is written to the logs"],"a":0,"e":"JPA (Jakarta Persistence API) is the standard for mapping Java objects to relational tables (ORM). Hibernate is the most popular implementation.\n`@Entity` says: instances of this class are rows of a table. `@Id` marks the primary key field. `@GeneratedValue` lets the database generate it, `@Column` customizes a column.\nEvery entity needs a no-argument constructor (can be protected) because the provider creates objects by reflection.","ec":"@Entity\n@Table(name = \"users\")\npublic class User {\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private Long id;\n\n    @Column(nullable = false, unique = true)\n    private String email;\n}","r":"@Entity = table row object. @Id = primary key.","g":["sp_jpa","sp_hibernate","primary_key","n_entity","api","orm"],"fa":"`@Entity` marks a Java class that maps to a table; `@Id` marks the field that is the primary key","cat":"spr"},{"id":"SPR-18","t":"m","l":2,"q":"What is the difference between LAZY and EAGER fetching in JPA?","o":["LAZY loads on first access; EAGER loads with the parent","LAZY is always faster, while EAGER is always slower","LAZY deletes the related data, while EAGER saves it","There is no difference at all between the two modes"],"a":0,"e":"A `User` may have many `Order`s. With EAGER, loading a user also loads all their orders right away, even if you never use them. With LAZY, orders are loaded from the database only when you first call `user.getOrders()`.\nDefaults: `@OneToMany` is LAZY, `@ManyToOne` is EAGER.\nLAZY avoids loading too much, but accessing a lazy field after the session/transaction has closed throws `LazyInitializationException`. A common recommendation is to use LAZY and fetch what you need explicitly (`JOIN FETCH` or `@EntityGraph`).","r":"Prefer LAZY, fetch explicitly what a use case needs.","g":["sp_lazy_loading","sp_jpa","n_plus_1","n_fetch","n_entitygraph","transaction"],"fa":"LAZY loads related data only when you first access it; EAGER loads it immediately together with the parent","cat":"spr"},{"id":"SPR-19","t":"m","l":3,"q":"What is the N+1 problem in JPA and how do you fix it?","o":["It means the database has N+1 tables in its schema","One query for N parents, then one per parent: `JOIN FETCH`","It means the application uses N+1 threads in total","It is a syntax error that JPQL reports at startup"],"a":1,"e":"Example: `findAll()` loads 100 users (1 query). Then your code loops and calls `user.getOrders()`, which is LAZY, so JPA runs 1 query per user: 100 more. Total 101 queries instead of 1 or 2.\nFixes: `select u from User u join fetch u.orders` loads everything with one JOIN; `@EntityGraph(attributePaths = \"orders\")` on the repository method; `@BatchSize` to load children in groups; or a DTO projection that selects only what you need.\nDetect it by turning on SQL logging and counting queries.","ec":"@Query(\"select u from User u join fetch u.orders\")\nList<User> findAllWithOrders();","r":"N+1 = 1 query for parents + 1 per child. Fetch join solves it.","g":["n_plus_1","sp_lazy_loading","sp_jpa","n_entitygraph","join","n_fetch"],"fa":"One query loads N parents, then one extra query per parent loads its children (N+1 queries total). Fix with `JOIN FETCH`, `@EntityGraph` or batch fetching","cat":"spr"},{"id":"SPR-20","t":"m","l":3,"q":"What is the persistence context and what is \"dirty checking\"?","o":["A log file where the database records its changes","A per-transaction entity cache; changes saved at commit","A security feature that limits who can read an entity","A way to copy tables from one database to another"],"a":1,"e":"When you load an entity inside a transaction, JPA keeps it in a persistence context (first-level cache) and remembers its original values. This entity is \"managed\".\nIf you call a setter on a managed entity, then at flush/commit JPA detects the difference (dirty checking) and runs the `UPDATE` itself. So inside a `@Transactional` method, `user.setName(\"x\")` is enough; `save()` is not required.\nThe same `findById` twice in one transaction also returns the same object without hitting the database again.","r":"Managed entities are auto-saved at commit when changed.","g":["sp_persistence_context","sp_jpa","transaction","sp_transactional"],"fa":"A per-transaction cache of managed entities; at commit, JPA compares them with their original state and issues UPDATEs automatically for changed ones, even without calling `save`","cat":"spr"},{"id":"SPR-21","t":"m","l":2,"q":"What is the role of `@ControllerAdvice` with `@ExceptionHandler`?","o":["It authenticates the users before each controller call","It centralizes exception handling and HTTP error replies","It schedules tasks to run at fixed times of the day","It logs every SQL statement that the app executes"],"a":1,"e":"Without it, an uncaught exception in a controller becomes a generic 500 error. With `@RestControllerAdvice` you write one class that catches exceptions from every controller and returns a clean JSON body with the right status code (404 for \"not found\", 400 for validation, 409 for conflicts...).\nIt keeps controllers free of try/catch and gives clients a predictable error format.","ec":"@RestControllerAdvice\npublic class ApiErrors {\n    @ExceptionHandler(UserNotFoundException.class)\n    public ResponseEntity<Map<String, String>> notFound(UserNotFoundException e) {\n        return ResponseEntity.status(404).body(Map.of(\"error\", e.getMessage()));\n    }\n}","r":"One @RestControllerAdvice class = consistent error responses.","g":["sp_controller_advice","status_code","http","n_class_file","json"],"fa":"It centralizes exception handling for all controllers, converting exceptions into consistent HTTP error responses","cat":"spr"},{"id":"SPR-22","t":"m","l":2,"q":"How do you validate request data in Spring Boot?","o":["Only with `if` statements repeated in every controller","Constraint annotations like `@NotBlank`, plus `@Valid`","With CSS rules that are applied on the client side","It is not possible to validate requests in Spring"],"a":1,"e":"Bean Validation (Jakarta Validation) lets you declare rules on fields. Put `@Valid` before the `@RequestBody` parameter and Spring checks the rules before running your method. On failure it throws `MethodArgumentNotValidException`, which you can convert to a 400 response.\nThe starter is `spring-boot-starter-validation`.\nNever trust client data: validate on the server even if the front-end also validates.","ec":"public record CreateUserRequest(\n    @NotBlank String name,\n    @Email @NotBlank String email,\n    @Size(min = 8) String password\n) {}","r":"@Valid + constraint annotations = declarative validation.","g":["sp_bean_validation","validation","sp_bean","sp_spring_boot","sp_starter","sp_request_body"],"fa":"Add Bean Validation annotations (`@NotBlank`, `@Email`, `@Size`...) on the fields and use `@Valid` on the controller parameter","cat":"spr"},{"id":"SPR-23","t":"m","l":2,"q":"Why use DTOs instead of exposing JPA entities directly in your API?","o":["DTOs always compile faster than the entities do","To control what the API exposes and keep it stable","Entities cannot be serialized to JSON in any way","Spring requires DTOs for every controller method"],"a":1,"e":"A DTO (Data Transfer Object) is a simple class (often a `record`) shaped for the API.\nIf you return an entity: you may leak sensitive fields, JSON serialization may trigger lazy loading (or fail), and any database change breaks your API contract.\nWith DTOs, the API and the database can evolve separately. Mapping is done by hand or with MapStruct.","r":"Entity = database shape. DTO = API shape.","g":["sp_dto","sp_jpa","api","sp_lazy_loading","json"],"fa":"To control exactly what leaves/enters the API (no password hashes or internal fields), avoid lazy-loading surprises and keep the API stable when the database changes","cat":"spr"},{"id":"SPR-24","t":"m","l":2,"q":"Which test annotation starts the FULL Spring application context, and which loads only the web layer?","o":["`@WebMvcTest` starts the full context; `@SpringBootTest` loads the web layer","`@SpringBootTest` starts the full context; `@WebMvcTest` loads the web layer","Both annotations always load the whole application context","`@DataJpaTest` starts the full context of the application"],"a":1,"e":"`@SpringBootTest` starts the whole application: slow but realistic (integration tests).\nTest slices load only the part you are testing, so they are faster:\n- `@WebMvcTest(UserController.class)`: only the web layer; you mock services and call endpoints with `MockMvc`.\n- `@DataJpaTest`: only JPA and repositories, with an in-memory database by default.\nFor pure unit tests of a service, skip Spring: use JUnit + Mockito.","r":"Slices (@WebMvcTest, @DataJpaTest) are fast; @SpringBootTest is the full app.","g":["sp_test_slice","integration_test","mock","n_slicing","unit_test","n_class_file"],"fa":"`@SpringBootTest` is full; `@WebMvcTest` loads only controllers and web components (with MockMvc)","cat":"spr"},{"id":"SPR-25","t":"m","l":2,"q":"What is Mockito used for in tests?","o":["Running the application in a production environment","Creating mocks for dependencies to test a class alone","Compiling Java source files into bytecode quickly","Managing database schema migrations between versions"],"a":1,"e":"Mockito creates fake versions of your dependencies. You tell the mock what to return (`when(...).thenReturn(...)`) and later verify calls (`verify(...)`).\nThis lets you test `OrderService` without a real database or payment provider.\nWith JUnit 5: `@ExtendWith(MockitoExtension.class)`, `@Mock` for fakes and `@InjectMocks` for the class under test.","ec":"@ExtendWith(MockitoExtension.class)\nclass OrderServiceTest {\n    @Mock PaymentGateway gateway;\n    @InjectMocks OrderService service;\n\n    @Test\n    void chargesTheCustomer() {\n        when(gateway.charge(100)).thenReturn(true);\n        assertTrue(service.pay(100));\n        verify(gateway).charge(100);\n    }\n}","r":"Mockito = fake dependencies for isolated unit tests.","g":["mock","unit_test","n_class_file","t_junit"],"fa":"Creating mock objects that stand in for real dependencies, so you test one class in isolation and verify its interactions","cat":"spr"},{"id":"SPR-26","t":"m","l":2,"q":"How does a request flow through Spring MVC?","o":["The browser calls the controller method straight away","`DispatcherServlet` maps the request to a controller","The database receives the request first and forwards it","The request is stored in a queue and processed later"],"a":1,"e":"1. The embedded servlet container (Tomcat) receives the HTTP request.\n2. Filters run (security, logging).\n3. The `DispatcherServlet` is the single entry point: it finds which controller method handles that URL and HTTP method.\n4. Arguments are resolved (`@PathVariable`, `@RequestBody` via Jackson) and the controller runs, calling services and repositories.\n5. The return value is converted (usually to JSON) and written to the response; exceptions go to `@ControllerAdvice`.","r":"Tomcat, filters, DispatcherServlet, controller, service, repository.","g":["sp_dispatcher","sp_servlet","middleware","json","d_mvc","http"],"fa":"The embedded server (Tomcat) receives it, the `DispatcherServlet` (front controller) maps it to a controller method, which calls services; the result is converted to JSON and returned","cat":"spr"},{"id":"SPR-27","t":"m","l":2,"q":"What does Spring Security do by default when you just add the starter?","o":["Nothing: you must configure every rule yourself first","It secures all endpoints, with a generated password","It encrypts the whole database with a default key","It blocks only POST requests and leaves GET open"],"a":1,"e":"Adding `spring-boot-starter-security` is \"secure by default\": every endpoint needs authentication, a default user `user` is created with a random password printed in the log, and CSRF protection is on for browser-style requests.\nYou then define a `SecurityFilterChain` bean to say which URLs are public, how users authenticate (JWT, OAuth2, form login) and which roles can do what.\nStore passwords hashed with `BCryptPasswordEncoder`, never in plain text.","ec":"@Bean\nSecurityFilterChain chain(HttpSecurity http) throws Exception {\n    http.authorizeHttpRequests(a -> a\n            .requestMatchers(\"/public/**\").permitAll()\n            .requestMatchers(\"/admin/**\").hasRole(\"ADMIN\")\n            .anyRequest().authenticated())\n        .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));\n    return http.build();\n}","r":"Spring Security: filter chain, authn then authz, BCrypt for passwords.","g":["sp_security","authn","authz","password_hashing","sp_starter","http"],"fa":"Secures all endpoints (login form / HTTP Basic with a generated password) until you define your own rules","cat":"spr"},{"id":"SPR-28","t":"m","l":1,"q":"What is JDBC?","o":["A JavaScript library for building database dashboards","The standard low-level Java API for running SQL","A Java build tool that packages the applications","A web framework that is used to build REST services"],"a":1,"e":"JDBC (Java Database Connectivity) lets Java talk to any relational database through a driver: open a `Connection`, create a statement, run SQL and read the `ResultSet`.\nJPA/Hibernate and Spring's `JdbcTemplate` are built on top of JDBC.\nAlways use `PreparedStatement` with `?` parameters and never concatenate user input into SQL (that is SQL injection).","ec":"String sql = \"SELECT name FROM users WHERE email = ?\";\ntry (PreparedStatement ps = conn.prepareStatement(sql)) {\n    ps.setString(1, email);          // safe: value is bound, not pasted\n    try (ResultSet rs = ps.executeQuery()) {\n        if (rs.next()) System.out.println(rs.getString(\"name\"));\n    }\n}","r":"JDBC = Java to SQL database. Always PreparedStatement.","g":["sp_jdbc","sql_injection","connection_pool","z_java","sql","d_relational"],"fa":"The standard low-level Java API to connect to relational databases and run SQL","cat":"spr"},{"id":"SPR-29","t":"m","l":1,"q":"What is a servlet and a servlet container (like Tomcat)?","o":["A servlet handles HTTP requests; Tomcat runs servlets","A servlet is a database server; Tomcat is a build tool","A servlet is a JavaScript function run in the browser","A servlet is a test file; Tomcat compiles Java code"],"a":0,"e":"A servlet is a Java class that receives an HTTP request and writes a response. It is the base technology of Java web applications.\nA servlet container (Tomcat, Jetty, Undertow) is the server that listens on a port, parses HTTP, manages threads and calls your servlets.\nSpring MVC is built on one servlet, the `DispatcherServlet`. Classic apps were packaged as WAR files and deployed in a Tomcat; Spring Boot embeds Tomcat inside a runnable JAR.","r":"Servlet = Java HTTP handler. Container = the server that runs it.","g":["sp_servlet","sp_dispatcher","http","z_java","container","sp_spring_boot"],"fa":"A servlet is a small Java class that handles HTTP requests; a container such as Tomcat runs servlets, receives the HTTP traffic and calls the right servlet","cat":"spr"},{"id":"SPR-30","t":"m","l":2,"q":"What is Jackson and what happens in `@RestController` when a method returns an object?","o":["Jackson is a test runner, so the returned object is ignored","Jackson is the default JSON library for converting objects","Jackson encrypts the returned data before sending it out","Jackson is a database where the object gets stored later"],"a":1,"e":"Jackson (`ObjectMapper`) serializes Java objects to JSON and deserializes JSON to Java objects. Spring Boot includes it with the web starter.\nUseful annotations: `@JsonIgnore` (hide a field), `@JsonProperty(\"user_name\")` (rename), `@JsonFormat` (date format).\nCommon issue: serializing a JPA entity with bidirectional relations can loop forever; DTOs avoid it.","r":"Jackson = Java object to/from JSON.","g":["sp_jackson","json","sp_rest_controller","sp_spring_boot","sp_starter","sp_jpa"],"fa":"Jackson is the default JSON library: Spring uses it to convert the returned object to JSON (and request JSON to objects)","cat":"spr"},{"id":"SPR-31","t":"m","l":2,"q":"What is Spring Boot Actuator?","o":["A UI framework that is used to build web pages","A module with health, metrics and info endpoints","A code generator that creates the controllers","A database driver for the relational databases"],"a":1,"e":"Add `spring-boot-starter-actuator` and you get endpoints to see how the app is doing: `/actuator/health` (is it up? is the database reachable?), `/actuator/metrics`, `/actuator/info`.\nOrchestrators like Kubernetes call the health endpoint for liveness and readiness probes. Metrics integrate with Prometheus/Micrometer.\nExpose only what you need and protect the rest: some endpoints reveal sensitive details.","r":"Actuator = health and metrics endpoints for operations.","g":["sp_actuator","probe","observability","kubernetes","sp_spring_boot","sp_starter"],"fa":"A module exposing operational endpoints such as `/actuator/health`, metrics and info, used for monitoring and Kubernetes probes","cat":"spr"},{"id":"SPR-32","t":"m","l":3,"q":"What is Spring AOP (aspect-oriented programming) typically used for?","o":["Writing the HTML templates for the views of an app","Adding logging or security around methods without edits","Compiling the project faster with fewer classes","Storing the user sessions between two requests"],"a":1,"e":"Some concerns appear in many places (logging, transactions, security checks, metrics). Copying that code into every method clutters the logic.\nAOP lets you define an aspect (advice) and where it applies (pointcut). Spring implements it with proxies that wrap your beans: `@Transactional`, `@Cacheable`, `@Async` and method security all work this way.\nBecause it is proxy-based, calls inside the same class are not intercepted (self-invocation).","ec":"@Aspect\n@Component\npublic class TimingAspect {\n    @Around(\"execution(* com.acme.service..*(..))\")\n    public Object time(ProceedingJoinPoint pjp) throws Throwable {\n        long t = System.nanoTime();\n        try { return pjp.proceed(); }\n        finally { System.out.println(pjp.getSignature() + \" took \" + (System.nanoTime() - t) / 1_000_000 + \" ms\"); }\n    }\n}","r":"AOP = reusable behavior around methods, implemented with proxies.","g":["sp_aop","sp_proxy","transaction","sp_transactional","sp_stereotype","n_cacheable"],"fa":"Adding cross-cutting behavior such as logging, transactions, security or timing around methods without changing their code, using proxies","cat":"spr"},{"id":"SPR-33","t":"m","l":3,"q":"Spring Boot 3 requires which Java version at minimum, and what package rename happened?","o":["Java 8 as the minimum; no package change at all","Java 17; `javax.*` packages became `jakarta.*`","Java 11 as the minimum; `java.*` became `jdk.*`","Java 21 as the minimum; `spring.*` became `boot.*`"],"a":1,"e":"Spring Boot 3 (Spring Framework 6) requires Java 17 or newer.\nIt also moved from Java EE to Jakarta EE 9+, so imports changed from `javax.persistence.*`, `javax.servlet.*`, `javax.validation.*` to `jakarta.persistence.*`, `jakarta.servlet.*`, `jakarta.validation.*`.\nIf you migrate an old project (Boot 2.x), this rename is the most common breaking change.","r":"Boot 3 = Java 17+ and jakarta.* imports.","g":["sp_spring_boot","sp_jakarta","j_jdk","semver","sp_starter","sp_autoconfig"],"cat":"spr"},{"id":"SPR-34","t":"m","l":2,"q":"What is the difference between `@RequestParam` and `@PathVariable`?","o":["They are identical; both read the value from the URL","`@PathVariable` is from the path; `@RequestParam` the query","`@RequestParam` is meant for reading JSON bodies only","`@PathVariable` can only be used on POST requests"],"a":1,"e":"Path variables identify a specific resource: `/users/{id}`.\nQuery parameters filter, sort or paginate a collection: `/users?role=admin&page=2`.\nBoth are bound to method parameters. `@RequestParam` can be optional with a default: `@RequestParam(defaultValue = \"0\") int page`.","r":"Path = which resource. Query = how to filter/sort it.","g":["sp_path_variable","path_param","query_param","sp_request_body","sp_rest_controller","http_method","endpoint"],"fa":"`@PathVariable` takes a value from the URL path (`/users/42`); `@RequestParam` takes it from the query string (`/users?role=admin`)","cat":"spr"},{"id":"SPR-35","t":"f","l":1,"q":"Explain Inversion of Control and Dependency Injection, and why Spring uses them.","a":"- Inversion of Control: your code no longer controls the creation and lifecycle of its collaborators; a container does.\n- Dependency Injection is the way IoC is applied: a class declares dependencies (constructor parameters) and the container supplies them.\n- Spring scans for beans (`@Component`, `@Service`...), builds the object graph at startup and injects dependencies.\n- Benefits: loose coupling (depend on interfaces), easy testing with mocks, central configuration, lifecycle management.\n- Example: `OrderService(PaymentGateway g)`; in production Spring gives a Stripe gateway, in tests you pass a mock.","g":["dependency_injection","sp_stereotype","dependency","interface","container"],"cat":"spr"},{"id":"SPR-36","t":"f","l":2,"q":"Walk me through building a REST endpoint in Spring Boot, from request to database.","a":"- Controller (`@RestController`): maps the URL, reads input (`@PathVariable`, `@RequestBody` with `@Valid`), returns a DTO and the right status (`ResponseEntity`).\n- Service (`@Service`): business rules and `@Transactional` boundaries.\n- Repository (`JpaRepository`): database access; entity with `@Entity`.\n- Error handling: `@RestControllerAdvice` turns exceptions into 400/404/409 responses.\n- Config: `application.yml`, profiles, secrets from environment variables.\n- Tests: unit tests with Mockito for services, `@WebMvcTest` for controllers, `@DataJpaTest` or Testcontainers for repositories.\n- Ops: Actuator health endpoint, structured logs.","g":["env_var","sp_rest_controller","n_app_props","sp_transactional","sp_path_variable","n_jparepo","sp_request_body","sp_spring_boot"],"cat":"spr"},{"id":"SPR-37","t":"f","l":3,"q":"What are the most common pitfalls with JPA/Hibernate and `@Transactional`?","a":"- N+1 queries: LAZY collections accessed in a loop; fix with `join fetch`, `@EntityGraph`, batch size or DTO projections.\n- `LazyInitializationException`: reading a lazy field outside the transaction; fetch what you need inside the service or use DTOs.\n- Self-invocation or private methods: proxy bypassed, so no transaction.\n- Checked exceptions do not roll back by default (`rollbackFor`).\n- Too-long transactions (calling slow HTTP services inside) hold database connections.\n- Returning entities directly from controllers: leaks fields and triggers lazy loading.\n- `open-in-view` (default true in Boot) hides lazy loading problems in the web layer; many teams disable it.","g":["sp_lazy_loading","transaction","j_checked_exc","sp_transactional","n_entitygraph","sp_hibernate","n_fetch","http"],"cat":"spr"},{"id":"SPR-38","t":"f","l":2,"q":"Spring vs Spring Boot vs Spring MVC vs Spring Data: what is each?","a":"- Spring Framework: core container (IoC/DI), AOP, transactions and the base of everything.\n- Spring MVC: the web module: controllers, `DispatcherServlet`, request mapping, JSON conversion.\n- Spring Data: simplifies data access (JPA, MongoDB, Redis...) with repository interfaces.\n- Spring Security: authentication and authorization.\n- Spring Boot: opinionated layer that auto-configures all of the above, adds starters, embedded server and Actuator.\n- In one line: Spring is the toolbox, Spring Boot is the pre-assembled workshop.","g":["sp_spring_boot","d_mvc","sp_dispatcher","sp_spring","sp_security","authn","authz","transaction"],"cat":"spr"},{"id":"SPR-39","t":"m","l":0,"q":"What is an annotation such as `@Override` or `@Service` in Java?","o":["A label (metadata) on code that the compiler or a framework reads","A comment that the compiler and frameworks always ignore","A mandatory import statement placed at the top of the file","A kind of loop that repeats over a list"],"a":0,"e":"Annotations start with `@` and sit above classes, methods or fields.\nExample: `@Override` tells the compiler to check that the method really overrides a parent method. `@Service` tells Spring to create and manage an object of that class.\nSpring uses annotations everywhere, so reading them is a core skill: `@RestController`, `@GetMapping`, `@Autowired`, `@Transactional`.","r":"Annotation = a label that frameworks read.","g":["z_annotation","sp_stereotype","z_compiler","n_override","z_java","sp_rest_controller"],"fa":"A label (metadata) attached to code that the compiler or a framework reads to change how it behaves","cat":"spr"},{"id":"SPR-40","t":"m","l":0,"q":"In Spring, what is a 'bean'?","o":["An object created and managed by the Spring container","A kind of database used for caching Spring objects","A Java keyword that marks any class as injectable","A test file that checks the Spring configuration"],"a":0,"e":"The Spring documentation: a bean is an object that is instantiated, assembled and managed by a Spring IoC container.\nInstead of writing `new OrderService()` everywhere, you let Spring create one and give it to the classes that need it (dependency injection).\nClasses marked with `@Component`, `@Service` or `@Repository` become beans.","r":"Bean = an object managed by Spring.","g":["sp_bean","sp_ioc","dependency_injection","container","object","sp_stereotype"],"fa":"An object that is created, assembled and managed by the Spring container","cat":"spr"},{"id":"SPR-41","t":"m","l":0,"q":"What is Apache Tomcat, and why do Spring Boot web apps often include it?","o":["An open source Java web server, embeddable in Boot","A database engine that is bundled with Spring Boot","A cloud provider that hosts Spring Boot applications","A build tool that packages Spring Boot applications"],"a":0,"e":"A Java web app needs a server that listens for HTTP requests and passes them to your code.\nTomcat is that kind of server. In the old style you installed Tomcat and deployed a WAR file into it.\nSpring Boot can embed Tomcat (or Jetty or Undertow) inside your application, so there is nothing to install: you run the JAR and the server starts.","r":"Tomcat = the web server inside most Spring Boot apps.","g":["sp_servlet","sp_spring_boot","z_java","n_javac","z_server","n_war"],"fa":"An open source web server for Java (an implementation of Jakarta Servlet and related specifications) that Spring Boot can embed so your app starts with `java -jar`","cat":"spr"},{"id":"SPR-42","t":"m","l":0,"q":"A Spring Boot web app starts with default settings. On which port does the embedded server listen?","o":["8080","80","443","5432"],"a":0,"e":"The Spring Boot reference says that by default the embedded server listens for HTTP requests on port 8080. The Spring quickstart opens `http://localhost:8080/hello`.\nYou can change it with `server.port=9090` in `application.properties`.\nFor comparison: HTTP normally uses 80 and HTTPS 443.","r":"Spring Boot default port: 8080.","g":["port","sp_config_props","sp_spring_boot","http","n_app_props","https"],"cat":"spr"},{"id":"SPR-43","t":"m","l":0,"q":"What is `application.properties` (or `application.yml`) in a Spring Boot project?","o":["The configuration file with the port and database URL","The main Java class that starts up the application","The Maven repository where dependencies are stored","The test report that is generated after the build"],"a":0,"e":"Spring Boot reads settings from this file in `src/main/resources`, so you can change behavior without changing code.\nExamples: `server.port=9090`, `spring.datasource.url=jdbc:postgresql://localhost:5432/shop`.\nDifferent environments can use different files (profiles), and secrets should come from environment variables, not from a committed file.","r":"application.properties = settings of the app.","g":["sp_config_props","sp_profile","n_app_props","sp_spring_boot","z_url","env_var"],"fa":"The configuration file where you set values such as the server port or the database URL","cat":"spr"},{"id":"SPR-44","t":"m","l":0,"q":"What are JPA (Jakarta Persistence) and Hibernate?","o":["JPA is a mapping specification; Hibernate implements it","Both are web servers that are used to run Java apps","JPA is a database engine; Hibernate is its backup tool","JPA is a testing tool; Hibernate is a build system"],"a":0,"e":"An ORM (object-relational mapper) lets you work with Java objects instead of writing SQL for every operation: it converts objects to rows and back.\nJPA defines the standard API (annotations like `@Entity`, `@Id`). Hibernate is software that implements it.\nJPA was called Java Persistence API; since the move to Jakarta EE it is Jakarta Persistence, and the package changed from `javax.persistence` to `jakarta.persistence`.","r":"JPA = the standard. Hibernate = the implementation.","g":["sp_jpa","sp_hibernate","orm","z_java","z_persistence","api"],"fa":"JPA is a specification for mapping Java objects to database tables; Hibernate is a popular implementation of it (an ORM)","cat":"spr"},{"id":"SPR-45","t":"m","l":0,"q":"What is start.spring.io (Spring Initializr)?","o":["A web tool that generates a Spring Boot project","A Spring-only database used for local testing","The test runner that ships with Spring Boot","A paid cloud service that hosts Spring apps"],"a":0,"e":"You choose options (build tool such as Maven or Gradle, language, Spring Boot version, dependencies like 'Spring Web'), click Generate, and download a zip with a working project: `pom.xml`, the main class and the folder structure.\nThe official Spring quickstart starts exactly like this. IDEs such as IntelliJ also have it built in.","r":"Initializr = project generator for Spring Boot.","g":["sp_spring_boot","sp_starter","generator","v_pom","v_maven"],"fa":"A web tool that generates a ready-to-run Spring Boot project skeleton with the dependencies you choose","cat":"spr"},{"id":"DP-01","t":"m","l":1,"q":"The Single Responsibility Principle says a class should…","o":["Have only one method","Have only one reason to change","Be used by only one other class","Never inherit"],"a":1,"e":"SRP (the S in SOLID) means a class should do one job, so only one kind of change request should ever force you to edit it.\nExample: a class that calculates an invoice AND saves it to the database AND sends the email changes when tax rules change, when the database changes and when the email template changes. Split it into three classes, each with one job.","r":"One class, one job, one reason to change.","g":["solid","srp","cohesion","class","z_database"],"cat":"oop"},{"id":"DP-02","t":"m","l":2,"q":"Which change best follows the Open/Closed Principle?","c":"def price(order):\n    if order.type == \"regular\": return order.total\n    if order.type == \"vip\":     return order.total * 0.9\n    # every new customer type edits this function","o":["Add another `if` branch each time a new type appears","Introduce a `PricingStrategy` interface and add a class per new type","Move the function into a separate utility module","Keep a global dictionary of discounts and edit it at runtime"],"a":1,"e":"Open/Closed means: open for extension, closed for modification. You should add new behavior by ADDING code, not by editing code that already works and is tested.\nWith a growing if/elif, every new customer type means editing (and risking) this function.\nWith a strategy interface, each type is its own small class; a new type is a new class and the old code stays untouched.","r":"Add new behavior with new code, not by editing working code.","g":["solid","ocp","polymorphism","strategy"],"fa":"Introduce a `PricingStrategy` interface and add new classes for new types","cat":"oop"},{"id":"DP-03","t":"m","l":2,"q":"`Square` extends `Rectangle`, and `set_width()` on a square also changes its height. Code that sets width=2, height=5 and expects area 10 breaks. Which principle is violated?","o":["Single Responsibility","Liskov Substitution","Interface Segregation","Dependency Inversion"],"a":1,"e":"Liskov Substitution says: anywhere the code expects a parent class, you must be able to give it a child class without breaking anything.\nCode written for Rectangle assumes width and height change independently. A Square breaks that assumption, so it is not a safe substitute even though 'a square is a rectangle' in math.\nFix: make them separate shapes (or immutable).","r":"A subclass must keep every promise its parent makes.","g":["solid","lsp","inheritance","immutable"],"cat":"oop"},{"id":"DP-04","t":"m","l":2,"q":"An interface `Worker` has `work()`, `eat()` and `sleep()`. A `Robot` must implement `eat()` with `raise NotImplementedError`. Which principle suggests a fix?","o":["Interface Segregation","Open/Closed","DRY","Law of Demeter"],"a":0,"e":"Interface Segregation says: do not force a class to depend on methods it does not use.\nOne big interface makes Robot fake an `eat()` method. Split it into small interfaces (Workable, Eatable) and let each class implement only what applies to it.","r":"Many small interfaces beat one big one.","g":["solid","isp","interface","n_sleep"],"cat":"oop"},{"id":"DP-05","t":"m","l":2,"q":"Dependency Inversion means…","o":["Subclasses call the methods of their parent classes in reverse","High-level modules depend on abstractions, not on concrete details","Dependencies are installed in the reverse order of their use","Inheritance is used in place of composition in every class"],"a":1,"e":"High-level code (business rules, like OrderService) should not depend directly on low-level details (like the Stripe library). Both should depend on an abstraction, e.g. a `PaymentGateway` interface.\nThen you can swap Stripe for PayPal, or for a fake in tests, without touching OrderService.","ec":"class OrderService:\n    def __init__(self, gateway: PaymentGateway):   # abstraction\n        self.gateway = gateway\n\nservice = OrderService(StripeGateway())   # concrete choice at the edge","r":"Depend on interfaces, plug in the concrete class from outside.","g":["solid","dip","interface","dependency_injection","n_init"],"fa":"High-level modules depend on abstractions, not on concrete low-level modules","cat":"oop"},{"id":"DP-06","t":"m","l":2,"q":"When is Builder a better fit than Factory?","o":["When you need one of several subclasses chosen at runtime","When an object has many optional parts assembled step by step","When you need exactly one instance in the whole program","When existing objects must be cloned instead of created"],"a":1,"e":"A Factory decides WHICH type of object to create (e.g. `make_notifier(\"sms\")` returns an SmsNotifier).\nA Builder handles HOW to assemble one complex object step by step, when it has many optional settings (e.g. an HTTP request with headers, timeout, retries).\nIn Python, keyword arguments with defaults often replace simple builders.","r":"Factory = which object. Builder = how to assemble it.","g":["design_pattern","factory","builder","keyword_arg","http"],"fa":"When an object needs many optional parts assembled step by step","cat":"oop"},{"id":"DP-07","t":"m","l":2,"q":"What is the main criticism of the Singleton pattern?","o":["It uses too much memory for the single object that it keeps","It adds hidden global state, so testing and parallelism get harder","It cannot be implemented in some languages, such as Python","It is always slower than a normal class in every case"],"a":1,"e":"A Singleton guarantees there is only one instance of a class and lets everyone grab it from anywhere.\nThat is basically a global variable: code depends on it silently, tests share its state and interfere with each other, and it is hard to replace with a fake.\nPrefer creating one instance at startup and passing it to whoever needs it (dependency injection).","r":"Singleton = global state in disguise. Prefer injecting the instance.","g":["singleton","global_state","dependency_injection","design_pattern","coupling"],"fa":"It introduces hidden global state and makes testing and parallelism harder","cat":"oop"},{"id":"DP-08","t":"m","l":2,"q":"What problem does the Repository pattern solve?","o":["Version control of the source code of a software project","Hiding persistence behind a collection-like interface","Caching HTTP responses to reduce the load on the server","Managing package dependencies between the modules"],"a":1,"e":"A repository is a class like `UserRepository` with simple methods: `get(id)`, `add(user)`, `list_active()`. All SQL or ORM code lives inside it.\nThe business logic only talks to the repository, so it does not care whether data comes from PostgreSQL, an API or a dictionary in memory.\nIn tests, you swap in an in-memory repository: fast and no database needed.","r":"Repository = a clean door between business logic and the database.","g":["repository","orm","abstraction","sql","api"],"fa":"Hiding persistence details behind a collection-like interface so domain logic does not depend on the ORM/SQL","cat":"oop"},{"id":"DP-09","t":"m","l":2,"q":"What is the main benefit of dependency injection?","o":["It produces fewer lines of code in every class of the system","Components get collaborators from outside, so they are easy to test","It makes the program run faster at runtime in all cases","It removes the need to write interfaces for the components"],"a":1,"e":"Without DI, a class creates what it needs inside itself (`self.db = PostgresDB()`), so it is glued to that choice.\nWith DI, the class receives it from outside (`def __init__(self, db)`). The caller decides which implementation to pass: the real one in production, a fake in tests.\nFastAPI's `Depends` is a DI system.","r":"Don't create your dependencies inside; receive them.","g":["dependency_injection","coupling","mock","n_init"],"fa":"Components receive their collaborators from outside, so they are loosely coupled and easy to test with fakes","cat":"oop"},{"id":"DP-10","t":"m","l":2,"q":"Which pattern is this?","c":"class Checkout:\n    def __init__(self, shipping_calc):\n        self.shipping_calc = shipping_calc\n\n    def total(self, cart):\n        return cart.subtotal + self.shipping_calc(cart)\n\nCheckout(express_shipping).total(cart)\nCheckout(free_shipping).total(cart)","o":["Strategy","Observer","Adapter","Template Method"],"a":0,"e":"Strategy puts interchangeable algorithms (here: ways to calculate shipping) behind the same interface, and lets you choose one at runtime.\nCheckout does not know or care which shipping rule it got; it just calls it. Adding a new rule needs no change in Checkout.\nIn Python a strategy can simply be a function.","r":"Strategy = swap the algorithm without changing the code that uses it.","g":["strategy","design_pattern","polymorphism","n_init"],"cat":"oop"},{"id":"DP-11","t":"m","l":2,"q":"Which pattern fits 'notify email, analytics and inventory services whenever an order is placed'?","o":["Observer: subscribers are notified of each new order","Singleton: one shared service handles every order","Builder: each order is assembled step by step","Prototype: each order is cloned from a template"],"a":0,"e":"Observer: an object (the subject) keeps a list of subscribers and notifies all of them when something happens.\nThe order code just announces 'order placed'; it does not know who listens. You can add a new listener (e.g. loyalty points) without touching the order code.\nIn bigger systems the same idea becomes an event bus or message queue.","r":"Observer = 'tell everyone who subscribed'.","g":["observer","design_pattern","message_queue","pub_sub","coupling"],"fa":"Observer (publish/subscribe)","cat":"oop"},{"id":"DP-12","t":"m","l":2,"q":"You must use a third-party SMS client whose interface differs from your `Notifier.send(to, text)`. Which pattern?","o":["Adapter","Facade","Decorator","Command"],"a":0,"e":"An Adapter is a small wrapper that converts one interface into the one your code expects, like a travel plug adapter.\nYour `SmsAdapter.send(to, text)` internally calls the vendor's `client.messages.create(dest=..., body=...)`.\nThe rest of your code keeps using `Notifier.send` and never knows the vendor's API.","r":"Adapter = translate one interface into another.","g":["adapter","interface","facade","design_pattern","coupling","api"],"cat":"oop"},{"id":"DP-13","t":"m","l":3,"q":"How does the GoF Decorator pattern differ from inheritance for adding behavior?","o":["It is identical to inheritance in how it adds new behavior","It wraps an object with the same interface, so behaviors stack","It requires multiple inheritance to combine the behaviors","It modifies the original class directly at compile time"],"a":1,"e":"The Decorator pattern wraps an object in another object that has the SAME interface and adds one extra behavior (logging, caching, retries).\nBecause wrappers look identical from outside, you can stack them in any combination at runtime: `Cached(Logged(SqlRepo()))`.\nWith inheritance you would need a subclass for every combination.","r":"Decorator pattern = wrap and add, same interface.","g":["design_pattern","composition","decorator","polymorphism","interface"],"fa":"It wraps an object with the same interface at runtime, so behaviors can be stacked dynamically","cat":"oop"},{"id":"DP-14","t":"m","l":2,"q":"'Favor composition over inheritance' mainly helps avoid…","o":["Using classes at all in the design of a program","Fragile deep hierarchies, where base changes ripple","Writing interfaces for every class of the program","Using polymorphism in the design of a program"],"a":1,"e":"Inheritance ('is-a') ties a child tightly to its parent: a change in the parent can break every child, and deep hierarchies get hard to understand.\nComposition ('has-a') builds an object from smaller parts it holds as attributes: a Car HAS an Engine. Parts can be swapped easily, even at runtime.\nUse inheritance only for true 'is-a' relationships and keep it shallow.","r":"Prefer 'has-a' (composition) to 'is-a' (inheritance).","g":["composition","inheritance","coupling","polymorphism","design_pattern"],"fa":"Fragile, deep hierarchies where changes in a base class ripple into subclasses","cat":"oop"},{"id":"DP-15","t":"m","l":3,"q":"Which line violates the Law of Demeter ('talk only to your immediate friends')?","o":["`total = order.total() + shipping`","`order.customer.address.city.upper()`","`self.repo.save(order, commit=True)`","`count = len(items) + len(extra)`"],"a":1,"e":"The Law of Demeter says a method should talk to its direct collaborators, not reach through them into their internals.\n`order.customer.address.city` means your code knows how Order, Customer and Address are built inside. If any of them changes, your code breaks.\nBetter: ask the nearest object for what you need, e.g. `order.shipping_city()`.","r":"Avoid long chains of dots into other objects' internals.","g":["coupling","encapsulation","n_demeter","cohesion","design_pattern"],"cat":"oop"},{"id":"DP-16","t":"m","l":1,"q":"In the test pyramid, which tests should you have the most of?","o":["End-to-end UI tests in the browser","Manual exploratory tests by testers","Fast, isolated unit tests of functions","Load and stress tests under traffic"],"a":2,"e":"The test pyramid: a wide base of many small, fast unit tests; a middle layer of integration tests (several parts together, e.g. code + database); a small top of end-to-end tests (the whole app, like a real user).\nUnit tests run in milliseconds and point exactly to the bug. End-to-end tests are slow and fragile, so keep only a few for critical paths.","r":"Many unit tests, some integration tests, few end-to-end tests.","g":["test_pyramid","unit_test","integration_test","e2e_test","z_database"],"fa":"Fast, isolated unit tests","cat":"oop"},{"id":"DP-17","t":"m","l":2,"q":"What should a unit test usually mock?","o":["The class under test, so that the test stays simple","External boundaries: network, database, clock, random","Pure helper functions that have no side effects","Nothing at all, because mocks are bad practice"],"a":1,"e":"Mock things that are slow, unpredictable or outside your control: HTTP APIs, the database, the current time, random numbers.\nDo NOT mock the code you are testing, or simple internal helpers: then the test only checks your mocks, and every refactor breaks it.","r":"Mock the boundaries, not your own logic.","g":["mock","unit_test","stub","fake","test_isolation","deterministic"],"cat":"oop"},{"id":"DP-18","t":"m","l":1,"q":"The TDD cycle is…","o":["Design, code and test, repeated in one long cycle","Red (failing test), green (make it pass), refactor","Test only after the release, then fix whatever failed","Write all the tests first, then write all the code"],"a":1,"e":"Test-Driven Development works in tiny loops:\n1. Red: write one small test for the next behavior. It fails, because the code does not exist yet.\n2. Green: write the minimum code to make it pass.\n3. Refactor: clean up the code while the test protects you.\nThen repeat with the next small behavior.","r":"Red → Green → Refactor.","g":["tdd","refactoring","unit_test","regression","edge_case","coverage"],"cat":"oop"},{"id":"DP-19","t":"m","l":1,"q":"Good modular design aims for…","o":["High coupling, low cohesion","Low coupling, high cohesion","High coupling, high cohesion","Low coupling, low cohesion"],"a":1,"e":"Cohesion: how well the things inside one module belong together (high = focused, good).\nCoupling: how much modules depend on each other's details (low = independent, good).\nWith low coupling and high cohesion, a change stays inside one module instead of rippling everywhere.","r":"Low coupling, high cohesion.","g":["coupling","cohesion","abstraction","encapsulation","solid","interface"],"cat":"oop"},{"id":"DP-20","t":"m","l":2,"q":"Why do immutable objects simplify concurrent code?","o":["They are faster to create than mutable ones in every case","They cannot change, so threads share them without locks","They always use less memory than mutable objects do","They are automatically saved to the database when created"],"a":1,"e":"Most concurrency bugs come from two threads changing the same data at the same time (race conditions).\nAn immutable object can never change, so any number of threads can read it at once with no risk and no locks.\nTo 'modify' it you create a new object, which other threads never see half-finished.","r":"No changes → no race conditions.","g":["immutable","race_condition","thread","mutable","lock","j_immutable_class"],"fa":"They cannot be changed after creation, so threads can share them without locks","cat":"oop"},{"id":"DP-21","t":"m","l":2,"q":"Which pattern provides a single simplified entry point to a complex subsystem (e.g. `VideoConverter.convert(file, \"mp4\")` hiding codecs, buffers, muxers)?","o":["Facade","Proxy","Adapter","Flyweight"],"a":0,"e":"A Facade is a simple front door to a complicated set of classes. Clients call one easy method; the facade coordinates the many internal steps.\nDifference with Adapter: an Adapter converts one interface to another; a Facade simplifies a whole subsystem.","r":"Facade = one simple front door to a complex system.","g":["facade","abstraction","interface","coupling","design_pattern"],"cat":"oop"},{"id":"DP-22","t":"m","l":3,"q":"Which pattern makes undo/redo and job queues natural?","o":["Command","Singleton","Iterator","Bridge"],"a":0,"e":"The Command pattern turns an action into an object, e.g. `AddTextCommand` with `execute()` and `undo()`.\nBecause actions are objects, you can store them in a history list (undo/redo), put them in a queue to run later, log them, or retry them.","r":"Command = an action stored as an object.","g":["design_pattern","n_command_pattern","observer"],"cat":"oop"},{"id":"DP-23","t":"m","l":1,"q":"Under Semantic Versioning, you remove a public function from a library at version 2.4.1. The next version is…","o":["2.4.2","2.5.0","3.0.0","2.4.1-beta"],"a":2,"e":"SemVer versions are MAJOR.MINOR.PATCH.\n- PATCH (2.4.2): bug fixes, nothing breaks.\n- MINOR (2.5.0): new features, old code still works.\n- MAJOR (3.0.0): breaking changes, old code may stop working.\nRemoving a public function breaks users who call it, so it is a MAJOR bump.","r":"Breaking change → MAJOR. New feature → MINOR. Fix → PATCH.","g":["semver","http_method","z_library","z_patch"],"cat":"oop"},{"id":"DP-24","t":"m","l":2,"q":"Why should you avoid `git rebase` on a branch others have already pulled?","o":["Rebase deletes the branch that it is applied to","Rebase rewrites history, so collaborators' copies diverge","Rebase is always much slower than a merge of the branch","Rebase cannot resolve conflicts, so a merge is needed"],"a":1,"e":"Rebase re-creates your commits on top of another branch. They get NEW commit IDs, so the history is rewritten.\nIf teammates already have the old commits, their copies no longer match, and a force-push can wipe out work they built on top.\nRule: rebase freely on your own local branch; on shared branches, merge instead.","r":"Never rewrite history others already have.","g":["rebase","merge","git_commit","v_git"],"fa":"Rebase rewrites commit history; collaborators' copies diverge and force-pushes can lose their work","cat":"oop"},{"id":"DP-25","t":"m","l":2,"q":"A class has 3,000 lines and handles HTTP parsing, billing rules and PDF generation. This code smell is called…","o":["Feature envy","God object","Shotgun surgery","Primitive obsession"],"a":1,"e":"A 'god object' knows and does too much. It breaks the Single Responsibility Principle: many unrelated reasons to change, hard to test, and every developer edits it, causing conflicts.\nFix gradually: write tests around it, then extract cohesive classes (HttpParser, BillingRules, PdfRenderer).","r":"Huge class doing everything = god object; split by responsibility.","g":["code_smell","srp","refactoring","d_god_object","http"],"cat":"oop"},{"id":"DP-26","t":"f","l":2,"q":"Explain SOLID with a short example for each letter.","a":"- S, Single Responsibility: `InvoiceCalculator` computes; `InvoiceRepository` saves; `InvoicePdf` renders.\n- O, Open/Closed: add a new `DiscountStrategy` class instead of editing a big `if/elif`.\n- L, Liskov Substitution: any `Storage` subclass must keep the same contract (no surprise exceptions, same meaning).\n- I, Interface Segregation: `Readable` and `Writable` instead of one fat `FileLike` interface.\n- D, Dependency Inversion: `OrderService` depends on a `PaymentGateway` abstraction; the Stripe implementation is injected.\n- Close with why: easier change, testing and teamwork. Do not over-engineer small code.","g":["solid","srp","ocp","lsp","isp","dip"],"cat":"oop"},{"id":"DP-27","t":"f","l":2,"q":"How do you approach a code review (as reviewer)?","a":"- Understand the intent first: ticket, description, tests. Run it if useful.\n- Priorities: correctness and edge cases, security, data/migration risk, design and readability, tests, performance, then style (automate style with linters/formatters).\n- Be specific and kind: ask questions, explain the why, suggest alternatives, mark small things as 'nit' (optional).\n- Keep PRs small; review promptly.\n- Approve when it improves the codebase, even if you would have written it differently.","g":["z_code_review","refactoring","code_smell","unit_test","edge_case","v_pull_request"],"cat":"oop"},{"id":"DP-28","t":"f","l":3,"q":"You inherit a 2,000-line legacy module with no tests and must change it. How do you proceed safely?","a":"- Read and map the behavior; find the area you must change and its seams.\n- Add characterization tests that capture current behavior (even strange behavior) around that area.\n- Refactor in small steps that do not change behavior: extract functions, rename, inject dependencies.\n- Make the change with tests in place; consider a feature flag.\n- For big rewrites use the Strangler Fig pattern: move pieces to new code gradually.\n- Ship in small increments, monitor, keep commits reviewable.","g":["refactoring","unit_test","regression","code_smell","feature_flag","test_pyramid"],"cat":"oop"},{"id":"DP-29","t":"m","l":1,"q":"What is the relationship between a class and an object?","o":["They are the same thing under two different names","A class is a blueprint; an object is something built from it","An object is a blueprint that is used to create classes","Classes exist only at runtime and objects only in the code"],"a":1,"e":"A class describes what data and behavior something has, like the plan of a house. An object is one real house built from that plan.\nYou can create many objects from one class, each with its own data: `ana = User(\"Ana\")` and `luis = User(\"Luis\")` are two objects of the class User.","r":"Class = blueprint. Object = one thing built from it.","g":["class","instance","object","z_oop","attribute","method"],"fa":"A class is a blueprint; an object (instance) is a concrete thing built from it","cat":"oop"},{"id":"DP-30","t":"m","l":1,"q":"What does encapsulation mean in OOP?","o":["Putting all the code of a program together in a single file","Keeping data with its methods, hiding details behind an interface","Copying objects so that the original is never changed","Using as many small classes as possible in the design"],"a":1,"e":"Encapsulation bundles data with the methods that work on it, and hides the internal details.\nExample: a BankAccount exposes `deposit()` and `withdraw()`, but nobody outside changes `balance` directly, so the class can enforce rules like 'no negative balance'.\nIn Python a leading underscore (`_balance`) signals 'internal, do not touch'.","r":"Encapsulation = hide the internals, expose a safe interface.","g":["encapsulation","interface","z_oop","object","class"],"fa":"Keeping an object's data and the methods that use it together, and hiding internal details behind a public interface","cat":"oop"},{"id":"DP-31","t":"m","l":1,"q":"`class Dog(Animal):` expresses which relationship?","o":["Dog HAS an Animal (composition)","Dog IS an Animal (inheritance)","Dog and Animal are unrelated types","Animal IS a Dog (inheritance)"],"a":1,"e":"This is inheritance: Dog is a kind of Animal. Dog automatically gets Animal's attributes and methods, and can add new ones or override (replace) existing ones.\nUse it only when 'X is a Y' is really true. For 'X has a Y' use composition (an attribute).","r":"Inheritance = 'is a'. Composition = 'has a'.","g":["inheritance","composition","z_oop","polymorphism","class"],"cat":"oop"},{"id":"DP-32","t":"m","l":1,"q":"What is polymorphism?","c":"for shape in [Circle(2), Square(3)]:\n    print(shape.area())","o":["A class that has many attributes and many methods inside","The same call works on different types, each running its own code","Changing the type of a variable while the program runs","Copying one method into many classes of the same program"],"a":1,"e":"Polymorphism means 'many forms': different classes offer the same method name, and the caller does not need to know which class it has.\nThe loop calls `area()` on each shape; Circle and Square each compute it their own way.\nThis removes long if/elif chains that check the type.","r":"Same method name, different behavior per class.","g":["polymorphism","interface","class","z_loop"],"fa":"The same call (`shape.area()`) works on different types, each running its own version","cat":"oop"},{"id":"DP-33","t":"m","l":1,"q":"What happens if you try `Shape()` when `Shape` is an abstract base class with an `@abstractmethod area()`?","o":["It works, and the `area()` method simply returns None","TypeError: it is not possible to instantiate an abstract class","It creates a default Circle object for you automatically","SyntaxError, which is raised when the file is loaded"],"a":1,"e":"An abstract class is a template that is not meant to be used directly. It declares methods that every subclass MUST implement.\nPython refuses to create an object from it. A subclass like Circle that implements `area()` can be created normally.\nThis guarantees that every shape really has an `area()` method.","r":"Abstract classes define the contract; only complete subclasses can be created.","g":["abc","abstraction","interface","j_abstract_class","n_builtin_exc"],"fa":"TypeError: can't instantiate abstract class","cat":"oop"},{"id":"DP-34","t":"m","l":1,"q":"What does the DRY principle say?","o":["Don't Repeat Yourself: each piece of knowledge lives in one place","Do Refactor Yearly: review and clean the code every year","Delete Redundant Years: remove old versions of the code","Document Right away: write the docs with each commit"],"a":0,"e":"If the same logic is copied in five places, a bug fix or rule change must be made five times, and someone will forget one.\nDRY says: put that logic in one function, class or constant and reuse it.\nBut do not merge code that only looks similar by accident; sometimes a little duplication is clearer than the wrong abstraction.","r":"One rule, one place.","g":["refactoring","n_dry","abstraction","class"],"fa":"Don't Repeat Yourself: each piece of knowledge should live in one place","cat":"oop"},{"id":"DP-35","t":"m","l":1,"q":"What is a design pattern?","o":["A ready-made library that you install and import","A named, proven solution to a common design problem","A color theme used in user interfaces","A type of database for storing code samples"],"a":1,"e":"Design patterns are reusable ideas, not code you download. Examples: Factory, Strategy, Observer, Adapter.\nThey give teams a shared vocabulary: saying 'use a Strategy here' explains a whole design in two words.\nUse them when they solve a real problem, not to show off.","r":"Pattern = named, reusable solution idea.","g":["design_pattern","solid","factory","singleton","observer"],"fa":"A proven, named solution to a common design problem that you adapt to your code","cat":"oop"},{"id":"DP-36","t":"m","l":1,"q":"What is refactoring?","o":["Adding new features to the existing code of a system","Changing the structure of code without changing its behavior","Rewriting the whole application in another language","Fixing the bugs that appear after a release to production"],"a":1,"e":"Refactoring improves the inside of the code (names, structure, duplication) while the behavior seen from outside stays exactly the same.\nExamples: renaming a variable, extracting a function, splitting a big class.\nTests are your safety net: run them after each small step to confirm nothing changed.","r":"Refactor = better structure, same behavior.","g":["refactoring","unit_test","z_variable","class"],"fa":"Changing the structure of code to make it cleaner without changing what it does","cat":"oop"},{"id":"DP-37","t":"m","l":1,"q":"In Git, what is the difference between `commit` and `push`?","o":["They are the same command, written with two different names","`commit` saves locally; `push` uploads commits to the remote","`push` saves locally, and `commit` uploads to the remote","`commit` deletes the old files from the repository"],"a":1,"e":"`git commit` records a snapshot of your staged changes with a message, only on your computer.\n`git push` sends your new commits to the shared remote repository so others can get them (`git pull`).\nTypical flow: edit → `git add` → `git commit -m \"...\"` → `git push`.","r":"commit = save locally. push = share remotely.","g":["git_commit","v_git","n_git_cmds","v_remote","repository"],"fa":"`commit` saves a snapshot in your LOCAL repository; `push` uploads your commits to the remote (e.g. GitHub)","cat":"oop"},{"id":"DP-38","t":"m","l":1,"q":"Why do developers create a Git branch for a new feature?","o":["To delete old code without touching the main branch of the repo","To work in isolation until changes are reviewed and merged","Branches make the code run faster when it is deployed","Git requires one separate branch for each file of the project"],"a":1,"e":"A branch is a separate line of work. You can commit freely on `feature/login` while `main` stays stable and deployable.\nWhen the feature is ready, you open a pull request, teammates review it, and it is merged into main.","r":"Branch = safe parallel workspace.","g":["git_branch","merge","v_git","v_pull_request","git_commit"],"fa":"To work on changes in isolation without affecting the main branch until they are reviewed and merged","cat":"oop"},{"id":"DP-39","t":"m","l":1,"q":"What is a merge conflict?","o":["Two branches that happen to have different names in the repository","Git cannot combine changes because both sides edited the same lines","A failed test that is caused by a recent commit in a branch","A repository that was deleted by mistake from the server"],"a":1,"e":"Git merges most changes automatically. When two branches change the SAME lines in different ways, Git cannot know which version is right.\nIt marks the spot with `<<<<<<<`, `=======` and `>>>>>>>`. You edit the file to keep the correct result, then commit.\nSmall, frequent merges reduce conflicts.","r":"Conflict = same lines changed on both sides; you decide.","g":["merge","git_branch","v_git","v_merge_conflict","n_equality"],"fa":"Git cannot combine changes automatically because both sides edited the same lines differently","cat":"oop"},{"id":"DP-40","t":"m","l":1,"q":"What does YAGNI ('You Aren't Gonna Need It') advise?","o":["Write every feature that you might need in the future","Don't build a feature until it is actually needed","Never write tests for code that is simple enough","Always apply a design pattern to the code you write"],"a":1,"e":"Code built for imagined future needs costs time now, adds complexity, and is often wrong when the future arrives.\nYAGNI says: build what the current requirement needs, keep it simple (KISS), and extend it when a real need appears.","r":"Build for today's need; keep it simple.","g":["refactoring","code_smell","design_pattern","tdd","n_yagni"],"fa":"Don't build functionality until it is actually needed","cat":"oop"},{"id":"DP-41","t":"m","l":1,"q":"The classic GoF design patterns are grouped into which three categories?","o":["Fast, medium and slow, by how quickly they run","Creational, Structural and Behavioral","Frontend, backend and database patterns","Public, private and protected patterns"],"a":1,"e":"The book \"Design Patterns\" by the Gang of Four (GoF) lists 23 patterns in three groups:\n- Creational: Singleton, Factory Method, Abstract Factory, Builder, Prototype. They control object creation.\n- Structural: Adapter, Decorator, Facade, Proxy, Composite, Bridge, Flyweight. They combine classes into larger structures.\n- Behavioral: Strategy, Observer, Command, Template Method, State, Iterator, Chain of Responsibility. They define how objects interact.\nA pattern is a proven solution to a recurring design problem, not code you copy.","r":"Creational = create. Structural = compose. Behavioral = interact.","g":["design_pattern","d_gof","d_chain","d_abstract_factory","d_template_method","d_flyweight"],"fa":"Creational (how objects are created), Structural (how objects are combined), Behavioral (how objects communicate)","cat":"oop"},{"id":"DP-42","t":"m","l":2,"q":"What is the difference between Factory Method and Abstract Factory?","o":["There is no difference between the two, only the name changes","Factory Method makes one product; Abstract Factory makes families of products","Factory Method is meant for threads; Abstract Factory for databases","Abstract Factory has no interfaces and works only with classes"],"a":1,"e":"Factory Method: a method returns an object of some interface and hides which concrete class is created: `NotificationFactory.create(\"email\")` gives an `EmailNotifier`.\nAbstract Factory: an object that creates several related products that must be consistent. Example: a `UiFactory` that creates `Button`, `Checkbox` and `Menu` for either a Windows or a Mac look; you switch the whole family by switching the factory.\nIn Spring, the container itself acts as a giant factory.","r":"Factory Method = one product. Abstract Factory = family of products.","g":["factory","d_abstract_factory","d_gof","interface","polymorphism"],"fa":"Factory Method: one method that decides which single product class to create. Abstract Factory: an interface to create whole families of related objects that belong together","cat":"oop"},{"id":"DP-43","t":"m","l":3,"q":"Which is the safest way to write a thread-safe Singleton in Java?","o":["A public static field that is initialized lazily with no synchronization","A single-element `enum`, or a holder class with a static final instance","A normal class with a public constructor that anyone can call","A class whose fields are all marked with the `volatile` keyword"],"a":1,"e":"Singleton means one instance for the whole application. Lazy initialization with `if (instance == null) instance = new X();` is NOT thread-safe: two threads could create two instances.\nSafe options:\n- `enum Config { INSTANCE; ... }`: the JVM guarantees one instance and it also survives serialization and reflection attacks (recommended by Effective Java).\n- Eager `private static final X INSTANCE = new X();`.\n- Initialization-on-demand holder idiom (a private static inner class holding the instance).\n- Double-checked locking works only if the field is `volatile`.\nIn Spring apps, usually let the container manage singleton beans instead.","ec":"public enum AppConfig {\n    INSTANCE;\n    public String env() { return \"prod\"; }\n}\n// AppConfig.INSTANCE.env()","r":"Java Singleton: prefer enum or let Spring manage it.","g":["singleton","d_enum_singleton","j_static","j_final","j_volatile","n_null_compare"],"fa":"A single-element `enum`, or a holder class / eager static final instance","cat":"oop"},{"id":"DP-44","t":"m","l":2,"q":"Which pattern does `new BufferedReader(new FileReader(\"a.txt\"))` illustrate?","o":["Singleton: only one reader can exist in the whole program","Decorator: BufferedReader wraps a Reader and adds buffering","Observer: the reader notifies its listeners of every new line","Prototype: the reader is cloned from an existing instance"],"a":1,"e":"The Decorator pattern wraps an object to add behavior, with the wrapper having the same interface as the wrapped object.\n`FileReader` reads characters from a file; `BufferedReader` wraps it and adds buffering and `readLine()`. You can keep stacking: `new GZIPInputStream(new FileInputStream(...))`.\nIt is a flexible alternative to creating many subclasses for each combination of features.","r":"Decorator = wrapper with the same interface that adds behavior.","g":["d_decorator","design_pattern","composition","polymorphism","j_autocloseable"],"fa":"Decorator: BufferedReader wraps another Reader and adds buffering while keeping the same interface","cat":"oop"},{"id":"DP-45","t":"m","l":2,"q":"Which pattern is behind `list.sort(Comparator.comparing(Person::getAge))`?","o":["Strategy: the algorithm is fixed; the comparison rule is passed in","Singleton: only one comparator exists in the whole program","Adapter: the list is converted to a different interface first","State: the list changes its behavior as its state changes"],"a":0,"e":"Strategy: define a family of interchangeable algorithms behind one interface and let the caller choose which to use.\nHere `Comparator` is the strategy interface. Sorting stays the same; you pass a different comparator (by age, by name) and the behavior changes without modifying `sort`.\nWith Java 8 lambdas, a strategy is often just a lambda.","r":"Strategy = swap behavior by passing an object/lambda.","g":["strategy","j_lambda","j_comparator","sorting"],"fa":"Strategy: the sorting algorithm is fixed, but the comparison rule is a replaceable object (or lambda) passed in","cat":"oop"},{"id":"DP-46","t":"m","l":2,"q":"What is the Template Method pattern?","o":["A class that generates HTML templates for the views of an app","A base class sets the algorithm skeleton; subclasses override steps","A pattern that is used to copy objects without their classes","A way to cache the results of calls to an expensive method"],"a":1,"e":"The superclass has a method with the overall steps in a fixed order (the template), and some steps are abstract or overridable. Subclasses fill in the details without changing the order.\nExample: `DataProcessor.process()` always does read, validate, transform, save; subclasses implement `transform()`.\nSpring's `JdbcTemplate` and `RestTemplate` follow a similar idea: they handle the boilerplate (connections, errors) and you supply the variable part.","r":"Template Method = fixed algorithm skeleton, customizable steps.","g":["d_template_method","design_pattern","n_jdbctemplate","n_resttemplate"],"fa":"A base class defines the fixed skeleton of an algorithm and lets subclasses override specific steps","cat":"oop"},{"id":"DP-47","t":"m","l":2,"q":"Which pattern describes Spring wrapping your bean to add transactions, caching or security without changing its code?","o":["Proxy","Singleton","Builder","Prototype"],"a":0,"e":"A Proxy is a stand-in object with the same interface as the real one. It receives the call first, adds something (a transaction, a security check, logging, lazy loading) and then forwards to the real object.\nSpring AOP creates proxies around beans for `@Transactional`, `@Cacheable` and `@PreAuthorize`. Hibernate also uses proxies for lazy-loaded entities.","r":"Proxy = same interface, controls access, adds behavior.","g":["d_proxy","sp_proxy","transaction","sp_transactional","sp_lazy_loading","n_cacheable"],"cat":"oop"},{"id":"DP-48","t":"m","l":2,"q":"Servlet filters and Spring Security's filter chain are examples of which pattern?","o":["Chain of Responsibility: each handler processes or forwards the request","Prototype: each filter makes a copy of the incoming request","Flyweight: all the filters share a single request object","Memento: the filters save the state of the request and restore it"],"a":0,"e":"In Chain of Responsibility, a request goes through a sequence of handlers. Each can handle it, modify it, stop it, or pass it on.\nIn a web app: logging filter, authentication filter, CORS filter, then the controller. If authentication fails, the chain stops and returns 401.\nOther examples: middleware in Express/FastAPI, approval workflows.","r":"Chain of Responsibility = pipeline of handlers.","g":["d_chain","middleware","sp_security","authn","cors"],"fa":"Chain of Responsibility: each handler processes the request or passes it to the next one","cat":"oop"},{"id":"DP-49","t":"m","l":2,"q":"Which pattern lets you treat a single object and a group of objects in a uniform way (a tree, like folders containing files and folders)?","o":["Composite","Command","Singleton","Observer"],"a":0,"e":"Composite: both a leaf (file) and a container (folder) implement the same interface, so client code can call `size()` on either one. A container calls the same method on all its children.\nExamples: file system, UI component trees (a panel containing buttons and panels), organization charts, menus.","r":"Composite = tree where leaf and group share one interface.","g":["d_composite","design_pattern","polymorphism","tree","recursion","interface"],"cat":"oop"},{"id":"DP-50","t":"m","l":2,"q":"What does the MVC pattern separate?","o":["Model (data), View (screen) and Controller (input handling)","Memory, Value and Cache, as the three layers of a program","Main, Variable and Class, as the three parts of a file","Method, Variable and Compiler, as the parts of a program"],"a":0,"e":"MVC splits an application into:\n- Model: the data and business rules.\n- View: the presentation (HTML page, JSON).\n- Controller: handles the user's request, calls the model and chooses the response.\nSpring MVC follows it: `@Controller` classes, services/entities as the model, Thymeleaf/JSON as the view. The goal: change the UI without touching the rules and vice versa.","r":"MVC = model, view, controller separation.","g":["d_mvc","sp_dispatcher","d_view","json","html","state"],"fa":"Model (data and rules), View (what the user sees), Controller (receives input and coordinates)","cat":"oop"},{"id":"DP-51","t":"m","l":3,"q":"The JVM caches `Integer` objects from -128 to 127 and reuses string literals from the string pool. Which pattern is this?","o":["Flyweight: share common immutable objects instead of making copies","Observer: objects get notified when another object changes state","Command: each request is wrapped inside its own object","Mediator: objects talk to each other through a central object"],"a":0,"e":"Flyweight saves memory by sharing objects that are identical and immutable instead of creating duplicates.\n`Integer.valueOf(100)` always returns the same cached object; identical string literals share one `String` in the pool.\nIt only works safely when the shared object is immutable.","r":"Flyweight = share identical immutable objects.","g":["d_flyweight","j_string_pool","immutable","j_jvm"],"fa":"Flyweight: share common immutable objects instead of creating many identical ones","cat":"oop"},{"id":"DP-52","t":"m","l":2,"q":"What is the difference between a DAO and a Repository?","o":["They are identical in all cases and can always replace each other","A DAO is table-oriented; a Repository is domain-oriented","DAO is a web framework and Repository is a type of database","Repository only works with NoSQL databases, never with SQL ones"],"a":1,"e":"DAO (Data Access Object): a class that hides the persistence details of one table or entity: `UserDao.insert`, `findById`.\nRepository (from Domain-Driven Design): a collection-like interface for domain objects: `users.add(user)`, `users.findByEmail(e)`; it may combine several tables and speaks the language of the domain.\nIn practice the two terms overlap a lot. Spring Data's `JpaRepository` is a repository abstraction on top of JPA.","r":"DAO = table-oriented. Repository = domain-oriented collection.","g":["repository","d_dao","n_jparepo","sp_jpa"],"fa":"A DAO is close to the database tables (CRUD per table); a Repository is closer to the domain, behaving like an in-memory collection of aggregates","cat":"oop"},{"id":"DP-53","t":"m","l":1,"q":"Which is an anti-pattern known as the \"God object\" (or God class)?","o":["A class that knows and does too much and is used by everything","A class with one clear and well-defined single purpose","A class that only contains static methods and no fields","An immutable class whose state is never changed after creation"],"a":0,"e":"A God object concentrates many responsibilities: data access, business rules, formatting and more. It becomes huge, hard to test and every change risks breaking something.\nCure: split it by responsibility (Single Responsibility Principle) into smaller cohesive classes.\nOther anti-patterns: spaghetti code (tangled flow), copy-paste programming, golden hammer (using one tool for everything), premature optimization.","r":"God object = one class doing everything. Split by responsibility.","g":["d_god_object","srp","object","class"],"cat":"oop"},{"id":"DP-54","t":"f","l":2,"q":"Which design patterns do you actually use in Java/Spring projects, and where?","a":"- Singleton: Spring beans are singletons by default (managed by the container).\n- Factory / Abstract Factory: `BeanFactory`, `Calendar.getInstance()`, `List.of(...)`.\n- Builder: `StringBuilder`, `Stream` builders, Lombok `@Builder`, `HttpRequest.newBuilder()`.\n- Strategy: `Comparator`, injecting different implementations of an interface.\n- Decorator: Java I/O streams (`BufferedReader`), wrapping services.\n- Proxy: `@Transactional`, `@Cacheable`, lazy loading in Hibernate.\n- Observer: events (`ApplicationEventPublisher`), listeners.\n- Template Method: `JdbcTemplate`, `RestTemplate`.\n- Chain of Responsibility: servlet and security filter chains.\n- Say when NOT to use a pattern: do not add one without a real problem (YAGNI).","g":["d_chain","d_abstract_factory","d_template_method","design_pattern","sp_transactional","j_stringbuilder","sp_lazy_loading","n_jdbctemplate"],"cat":"oop"},{"id":"DP-55","t":"f","l":1,"q":"What is a design pattern, and why do interviewers ask about them?","a":"- A reusable, named solution to a common design problem in a given context (not a library, not copy-paste code).\n- Gives teams a shared vocabulary: saying \"use a strategy here\" explains a lot in one sentence.\n- Interviewers check that you can recognize a problem shape (many ways to do X, add behavior dynamically, notify many listeners) and choose a simple solution.\n- Name the pattern, state the problem it solves, give a Java example, mention trade-offs (more classes, more indirection).\n- Avoid over-engineering: simplest code that works first, patterns when change pressure appears.","g":["design_pattern","z_trade_off","z_java","z_library"],"cat":"oop"},{"id":"DP-56","t":"m","l":0,"q":"What is object-oriented programming (OOP) in one sentence?","o":["Writing code only with real-world objects such as cars","Organizing code into objects that bundle data and behavior","Writing programs that contain no functions","Running a program on several computers at once"],"a":1,"e":"In OOP you model things of your program as objects. An object keeps its data in fields and exposes actions through methods. For example, an `Account` object has a `balance` and a `deposit()` method.\nBenefits listed by the Java tutorial: modularity, information hiding, code re-use and easy debugging or replacement of one object.\nJava, Python, C# and C++ support it.","r":"OOP = objects with data + behavior.","g":["z_oop","object","class","z_java"],"fa":"Organizing code into objects that bundle data (state) and behavior (methods)","cat":"oop"},{"id":"DP-57","t":"m","l":0,"q":"Which list contains the four classic pillars of OOP?","o":["Encapsulation, abstraction, inheritance, polymorphism","Compilation, linking, loading, execution","Frontend, backend, database, cloud","Confidentiality, integrity, availability, authentication"],"a":0,"e":"- Encapsulation: hide the internal data and let others use it only through methods.\n- Abstraction: show only what is needed and hide the complexity.\n- Inheritance: a class can reuse and extend another one (a Dog is an Animal).\n- Polymorphism: different objects can answer the same method call in their own way (`speak()` for Dog and Cat).\nInterviewers ask for these four constantly.","r":"Encapsulation, abstraction, inheritance, polymorphism.","g":["encapsulation","abstraction","inheritance","polymorphism","z_oop"],"cat":"oop"},{"id":"DP-58","t":"m","l":0,"q":"Library vs framework: what is the key difference?","o":["You call a library; a framework controls the flow and calls you","They are exactly the same thing, with two different names","A library is paid software and a framework is always free","A framework is always smaller and simpler than a library"],"a":0,"e":"Martin Fowler describes a library as a set of functions that you call. A framework embodies an abstract design, and its code calls yours: 'Don't call us, we'll call you'.\nExamples: `requests` and Jackson are libraries. Spring Boot and Django are frameworks.\nMDN adds that a framework is a library that offers opinions about how software gets built.","r":"Library: you call it. Framework: it calls you.","g":["z_framework","z_library","sp_spring_boot","sp_jackson"],"fa":"You call a library's code when you need it; a framework has the main flow and calls your code at points it defines (inversion of control)","cat":"oop"},{"id":"DP-59","t":"m","l":0,"q":"In software, what is a 'dependency'?","o":["A bug that only appears when another bug exists in the code","Something your code needs to work: a library, package or service","A very old piece of code that nobody dares to change","A deployment deadline that is set by the whole team"],"a":1,"e":"If your app uses the library `requests` to call APIs, then `requests` is a dependency.\nA database or another service your app calls is also a dependency.\nTools such as Maven (Java), pip (Python) and npm (JavaScript) download and manage dependencies for you.\n'Dependency injection' is a different but related idea: passing what a class needs from outside.","r":"Dependency = something you rely on.","g":["dependency","z_package_manager","dependency_injection","z_library","javascript","v_maven"],"fa":"Something your code needs in order to work: a library, a package, or another service","cat":"oop"},{"id":"DP-60","t":"m","l":0,"q":"What is a bug, and what is debugging?","o":["A bug is a flaw in software; debugging is finding and fixing its cause","A bug is a virus; debugging is installing an antivirus program","A bug is an unfinished feature; debugging is deleting it","A bug is a test; debugging is the act of writing that test"],"a":0,"e":"A bug is an error in the code, design or configuration that produces a wrong or unexpected result.\nDebugging is the process: reproduce the problem, find where the real behavior differs from the expected one, fix the cause, and add a test so it does not come back.\nTools: logs, print statements, and the debugger in an IDE where you can pause the program and look at variables.","r":"Bug = flaw. Debugging = find and fix it.","g":["z_bug","z_ide","unit_test","exception","logs"],"fa":"A bug is a flaw that makes software behave wrongly; debugging is finding and fixing its cause","cat":"oop"},{"id":"DP-61","t":"m","l":0,"q":"What is a code review?","o":["Counting how many lines of code someone has written","Another developer reads your changes before they are merged","The compiler checking the syntax of all the files","A demo of the finished product for a customer"],"a":1,"e":"In most teams you cannot put code in the main branch alone. You open a pull request, and teammates comment on it.\nA review looks for bugs, unclear names, missing tests, security problems and consistency with the rest of the code.\nGood reviews are polite and specific, and they teach both sides something.","r":"Code review = teammates check your change before merging.","g":["z_code_review","v_pull_request","refactoring","unit_test","git_branch"],"fa":"Another developer reads your changes before they are merged, to catch bugs, improve quality and share knowledge","cat":"oop"},{"id":"DP-62","t":"m","l":0,"q":"What is SOLID?","o":["Five OO design principles: SRP, OCP, LSP, ISP and DIP","A cloud storage product for large files","A type of database that stores solid objects","Five Agile ceremonies held during a sprint"],"a":0,"e":"SOLID is a set of five guidelines to keep object-oriented code easy to change. They were introduced by Robert C. Martin, and the acronym was coined later by Michael Feathers.\n- S: a class should have one reason to change.\n- O: extend behavior without modifying existing code.\n- L: a subclass must be usable wherever its parent is expected.\n- I: prefer small, focused interfaces.\n- D: depend on abstractions, not concrete classes.","r":"SOLID = five design principles (SRP, OCP, LSP, ISP, DIP).","g":["solid","srp","ocp","lsp","isp","dip"],"fa":"Five object-oriented design principles: Single responsibility, Open-closed, Liskov substitution, Interface segregation, Dependency inversion","cat":"oop"},{"id":"DP-63","t":"m","l":0,"q":"What is the 'Gang of Four' (GoF)?","o":["Four authors of the 1994 Design Patterns book, with 23 patterns","A security team that reviews code before every release","The four people who founded the Git project in 2005","A testing method that has four steps to follow"],"a":0,"e":"Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides wrote 'Design Patterns: Elements of Reusable Object-Oriented Software' (1994).\nIt catalogs 23 patterns in three groups: creational (how objects are created, e.g. Singleton, Builder), structural (how they are composed, e.g. Adapter, Decorator) and behavioral (how they interact, e.g. Observer, Strategy).","r":"GoF = authors of the 23 classic design patterns.","g":["d_gof","design_pattern","object","o_helm","singleton"],"fa":"Four authors of the 1994 book Design Patterns, which describes 23 classic object-oriented patterns","cat":"oop"},{"id":"DP-64","t":"m","l":0,"q":"What is 'technical debt'?","o":["Money that is owed to cloud providers for unpaid usage","Extra future work caused by choosing a quick or messy solution now","The price of buying new computers for the whole team","Unpaid software licenses that must be renewed this year"],"a":1,"e":"The metaphor: taking a shortcut is like borrowing money. You get speed now, but you pay interest later in the form of bugs, slow changes and confusing code.\nSome debt is a conscious, reasonable choice (ship the MVP first). Debt that is never repaid slows the team more and more.\nRefactoring and tests are the usual way to pay it back.","r":"Technical debt = shortcut now, extra work later.","g":["z_tech_debt","refactoring","code_smell","coupling","z_mvp"],"fa":"The extra future work caused by choosing a quick or messy solution now instead of a better one","cat":"oop"},{"id":"DP-65","t":"f","l":0,"q":"Explain what a class, an object, a field and a method are to a beginner.","a":"- A class is a blueprint (for example `Bicycle`): it describes what every bicycle has and can do.\n- An object is one real thing created from that blueprint (`Bicycle bike1 = new Bicycle();`). Two objects from the same class keep their own data.\n- Fields store the state of the object: `speed`, `gear`.\n- Methods are its behavior, the actions it can perform: `speedUp()`, `applyBrakes()`.\n- Encapsulation: keep the fields private and let others use the object only through its methods.","g":["class","object","z_oop","encapsulation"],"cat":"oop"},{"id":"API-01","t":"m","l":2,"q":"Which HTTP method is NOT idempotent by definition?","o":["GET","PUT","DELETE","POST"],"a":3,"e":"Idempotent means: sending the same request once or ten times leaves the server in the same final state.\nGET only reads. PUT sets a resource to a given value (setting it twice changes nothing more). DELETE removes it (deleting twice: still deleted).\nPOST usually CREATES something: two identical POSTs to `/orders` can create two orders. That is why retrying a POST is risky.","r":"POST creates → repeating it can create duplicates.","g":["idempotent","http_method","http"],"cat":"api"},{"id":"API-02","t":"m","l":1,"q":"What is the difference between PUT and PATCH?","o":["PUT creates a resource; PATCH deletes a resource","PUT replaces the whole resource; PATCH updates part of it","PATCH is idempotent by definition, but PUT is not","There is no difference, both update in the same way"],"a":1,"e":"PUT sends the COMPLETE new version of a resource and replaces the old one. Fields you leave out may be reset.\nPATCH sends only the fields that change, e.g. `{\"email\": \"new@x.com\"}`.\nPUT is idempotent; PATCH is not guaranteed to be (e.g. 'add 1 to counter').","r":"PUT = replace all. PATCH = change some fields.","g":["http_method","idempotent","rest","json","endpoint"],"fa":"PUT replaces the whole resource; PATCH applies a partial update","cat":"api"},{"id":"API-03","t":"m","l":1,"q":"A logged-in user requests another tenant's invoice. Which status code is most appropriate?","o":["401 Unauthorized, because the user is not allowed","403 Forbidden (or 404, to hide that it exists)","400 Bad Request, because the id is not valid","500 Internal Server Error, because the access failed"],"a":1,"e":"401 means 'I don't know who you are': credentials are missing or invalid (despite its name 'Unauthorized').\n403 means 'I know who you are, but you are not allowed to do this'.\nThe user is logged in but the invoice is not theirs, so 403. Many APIs answer 404 instead, so attackers cannot even learn that the invoice exists.","r":"401 = who are you? 403 = you can't do that.","g":["status_code","authn","authz","access_control","http","header"],"fa":"403 Forbidden (or 404 to hide existence)","cat":"api"},{"id":"API-04","t":"m","l":1,"q":"A successful `POST /users` that creates a user should ideally return…","o":["200 OK with an empty body and no extra headers","201 Created with a `Location` header for the new resource","204 No Content with no body and no headers","302 Found with a redirect to the list of users"],"a":1,"e":"201 Created tells the client precisely that something new was created.\nThe `Location` header gives the URL of the new resource (e.g. `/users/42`), and the body usually contains the created user.\n200 means generic success; 204 means success with no body (common for DELETE).","r":"Created something → 201 + Location.","g":["status_code","header","http_method","z_url"],"fa":"201 Created with a `Location` header pointing to the new resource","cat":"api"},{"id":"API-05","t":"m","l":2,"q":"FastAPI receives a body that fails Pydantic validation. Default response status?","o":["400","404","422","500"],"a":2,"e":"FastAPI validates the request body with Pydantic models. If a field is missing or has the wrong type, it automatically returns 422 Unprocessable Entity, with a list explaining which field failed and why.\nYour endpoint code never runs. 400 is a more generic 'bad request'.","r":"FastAPI validation error → 422.","g":["status_code","validation","json","endpoint","api"],"cat":"api"},{"id":"API-06","t":"m","l":2,"q":"A client exceeds the rate limit. Which status and header are standard?","o":["503 Service Unavailable with a `Cache-Control` header","429 Too Many Requests with a `Retry-After` header","403 Forbidden with a `WWW-Authenticate` header","400 Bad Request with a custom `X-Error` header"],"a":1,"e":"429 Too Many Requests means 'you are sending requests too fast'.\nThe `Retry-After` header tells the client how many seconds to wait before trying again.\nGood clients respect it and back off instead of hammering the server.","r":"Rate limited → 429 + Retry-After.","g":["rate_limit","status_code","n_retry_after","retry_backoff","header","http"],"fa":"429 Too Many Requests with `Retry-After`","cat":"api"},{"id":"API-07","t":"m","l":2,"q":"Which statement about a standard signed JWT (JWS) is true?","o":["Its payload is encrypted, so nobody except the server can read it","Its payload is only base64url-encoded; the signature stops edits","It can be revoked at once on the server side by default","It must always be stored in the localStorage of the browser"],"a":1,"e":"A JWT has three parts: header.payload.signature. The payload is only encoded (base64url), NOT encrypted: anyone can decode and read it (try jwt.io).\nThe signature, made with the server's secret key, proves the token was issued by the server and not modified. If someone changes the payload, the signature no longer matches.\nSo never put passwords or secrets in a JWT.","r":"JWT payload is readable by anyone; the signature only stops tampering.","g":["jwt","token","encoding","hmac","asymmetric","session","cookie"],"fa":"Its payload is only base64url-encoded; anyone can read it, but the signature prevents tampering","cat":"api"},{"id":"API-08","t":"m","l":3,"q":"Main drawback of stateless JWT access tokens?","o":["They are too large to send","They are hard to revoke before expiry","They require a database lookup on every request","They only work with OAuth"],"a":1,"e":"The server validates a JWT just by checking its signature and expiry, without looking anything up. That is fast, but it also means the server cannot easily 'cancel' a token: it stays valid until it expires.\nCommon solutions: short-lived access tokens (5-15 minutes) plus refresh tokens that CAN be revoked, or a denylist of revoked token IDs.","r":"JWTs are hard to revoke → keep them short-lived.","g":["jwt","stateless","token","session","cookie","authz","authn"],"cat":"api"},{"id":"API-09","t":"m","l":2,"q":"For a browser web app, where is a session/auth token safest from XSS theft?","o":["In localStorage, where scripts of the page can read it","In a global JavaScript variable inside the page","In an HttpOnly, Secure, SameSite cookie","In the URL query string of each request"],"a":2,"e":"If an attacker injects JavaScript into your page (XSS), that script can read localStorage and JS variables and send your token away.\nAn HttpOnly cookie cannot be read by JavaScript at all; the browser just sends it with requests. Secure = only over HTTPS; SameSite = not sent on most cross-site requests.\nCookies need CSRF protection, which SameSite mostly provides.","r":"Auth token in a browser → HttpOnly + Secure + SameSite cookie.","g":["cookie","httponly","xss","csrf","javascript","web_storage"],"fa":"An HttpOnly, Secure, SameSite cookie","cat":"api"},{"id":"API-10","t":"m","l":3,"q":"Which OAuth 2.0 flow is recommended for single-page apps and mobile apps?","o":["Implicit flow","Resource Owner Password Credentials","Authorization Code with PKCE","Client Credentials"],"a":2,"e":"Apps running on a user's device cannot keep a secret (anyone can inspect the code).\nAuthorization Code + PKCE adds a one-time random 'proof' so that even if someone steals the authorization code, they cannot exchange it for tokens.\nThe Implicit and Password flows are deprecated. Client Credentials is for server-to-server calls with no user.","r":"Browser/mobile login with OAuth → Authorization Code + PKCE.","g":["oauth","token","n_oidc","cors","origin","authz"],"cat":"api"},{"id":"API-11","t":"m","l":2,"q":"What is middleware in a web framework?","o":["A database driver that connects the app to the database engine","Code that wraps each request and response, like logging or auth","A frontend library that is used for building user interfaces","A message broker that delivers events between the services"],"a":1,"e":"Middleware is code that runs before and/or after EVERY request, around your endpoint functions, like layers of an onion.\nTypical uses: logging, measuring response time, checking authentication, adding CORS headers, handling errors.\nThe order matters: e.g. authentication must run before your route logic.","r":"Middleware = code that runs around every request.","g":["middleware","endpoint","cors","authn"],"fa":"Code that wraps every request/response, e.g. logging, auth, CORS, timing","cat":"api"},{"id":"API-12","t":"m","l":2,"q":"Which statement about CORS is correct?","o":["It protects your API from curl and from server-to-server calls","It is enforced by browsers; the server lists the allowed origins","It encrypts the traffic that moves between browser and server","It replaces authentication on the API for trusted websites"],"a":1,"e":"Browsers block a web page from reading responses from a different origin (domain/port) by default: the same-origin policy.\nCORS is how a server says 'it's OK, pages from https://myapp.com may read my responses', via `Access-Control-Allow-Origin`.\nOnly browsers enforce it. curl, Postman or another server ignore CORS completely, so it is not a security wall for your API.","r":"CORS is a browser rule, not API protection.","g":["cors","origin","header","http","cookie","json"],"fa":"It is enforced by browsers; the server declares allowed origins via `Access-Control-Allow-Origin`","cat":"api"},{"id":"API-13","t":"m","l":2,"q":"Listing 50 orders then accessing `order.customer.name` in a loop triggers 51 queries. In Django, the usual fix for this foreign key is…","o":["`prefetch_related(\"customer\")`","`select_related(\"customer\")`","`.only(\"customer\")`","`.raw()`"],"a":1,"e":"This is the N+1 problem: 1 query to get the orders, then 1 extra query per order to fetch its customer.\n`select_related(\"customer\")` loads orders and customers together in one query with a SQL JOIN.\n`prefetch_related` uses a second query for all related rows at once (for many-to-many or reverse relations). In SQLAlchemy: `joinedload` / `selectinload`.","r":"Loop that queries per item = N+1. Load related data up front.","g":["n_plus_1","orm","join","foreign_key","sql"],"cat":"api"},{"id":"API-14","t":"m","l":2,"q":"In SQLAlchemy, what is the `Session` primarily?","o":["An HTTP session that identifies the user who is logged in","A unit of work that tracks loaded objects and flushes changes","A connection string that points to the database server","A migration tool that changes the schema of the database"],"a":1,"e":"The SQLAlchemy Session keeps track of the objects you loaded or added. When you change them, it remembers what changed.\nOn `commit()`, it sends all the changes to the database together as one transaction.\nUse one session per request (or unit of work), and never share a session between threads.","r":"Session = tracks your changes and commits them together.","g":["orm","transaction","connection_pool","sql","table"],"fa":"A unit of work that tracks loaded objects and flushes changes in a transaction","cat":"api"},{"id":"API-15","t":"m","l":2,"q":"What does `Depends(get_db)` in a FastAPI endpoint signature do?","o":["It declares a Python import that the function needs in order to run","It calls `get_db` and injects the result, with cleanup after yield","It creates a background task that runs after the response","It validates the response of the endpoint before it is sent"],"a":1,"e":"FastAPI sees `db = Depends(get_db)`, calls `get_db()` for each request and passes the result into your function.\nIf `get_db` uses `yield`, the code after yield (e.g. closing the DB session) runs after the response.\nIn tests you can replace it: `app.dependency_overrides[get_db] = fake_db`.","ec":"def get_db():\n    db = SessionLocal()\n    try:\n        yield db\n    finally:\n        db.close()\n\n@app.get(\"/users/{uid}\")\ndef read_user(uid: int, db = Depends(get_db)):\n    return db.get(User, uid)","r":"Depends = FastAPI's dependency injection.","g":["dependency_injection","endpoint","n_yield","j_finally"],"fa":"Tells FastAPI to call `get_db` and inject its result (dependency injection), including generator cleanup","cat":"api"},{"id":"API-16","t":"m","l":3,"q":"In FastAPI you must call a slow, blocking SDK. Which option avoids blocking the event loop?","o":["Call it directly inside an `async def` endpoint, as usual","Use a plain `def` endpoint, or wrap it with `asyncio.to_thread`","Add `await` in front of the synchronous call to the SDK","Increase the timeout of the server so that the call can finish"],"a":1,"e":"`async def` endpoints run directly on the event loop, which must never be blocked.\nFastAPI runs plain `def` endpoints in a pool of worker threads, so a blocking call only blocks that thread.\nInside async code, `await asyncio.to_thread(sdk.call)` moves the blocking call to a thread. You cannot `await` a normal (non-async) function.","r":"Blocking library → plain def endpoint or to_thread.","g":["event_loop","blocking","async_await","thread","n_to_thread","n_sdk"],"fa":"Declare the endpoint with plain `def` (runs in a threadpool) or wrap the call with `run_in_threadpool`/`asyncio.to_thread`","cat":"api"},{"id":"API-17","t":"m","l":2,"q":"WSGI vs ASGI: what does ASGI add?","o":["Template rendering for HTML pages on the server side","Async support, including WebSockets and long-lived connections","An ORM that maps database tables to Python classes","Static file serving, and nothing else on top of WSGI"],"a":1,"e":"WSGI and ASGI are standards for how a Python web server talks to your web app.\nWSGI (Flask, classic Django, served by Gunicorn) is synchronous: one request per worker at a time, plain request/response.\nASGI (FastAPI, modern Django, served by Uvicorn) supports async code, WebSockets and long-lived connections.","r":"WSGI = sync. ASGI = async + WebSockets.","g":["wsgi_asgi","websocket","http","coroutine","async_await","event_loop"],"fa":"Async support including WebSockets and long-lived connections","cat":"api"},{"id":"API-18","t":"m","l":3,"q":"Why is cursor (keyset) pagination preferred over `OFFSET` for large, changing datasets?","o":["It supports jumping directly to any page number of the results","OFFSET skips rows and slows down; a cursor uses an index","Cursor pagination does not need any index on the table","OFFSET is not valid SQL in most of the databases"],"a":1,"e":"`OFFSET 100000 LIMIT 20` makes the database read and throw away 100,000 rows, so deep pages are slow. If rows are inserted while the user pages, items can be skipped or shown twice.\nCursor pagination remembers the last item seen and asks for `WHERE id > 12345 ORDER BY id LIMIT 20`, which uses an index and is always fast and stable.\nTrade-off: no 'jump to page 37'.","r":"Large or live lists → cursor pagination.","g":["pagination","index","sql","table","n_sql_clauses","rest"],"fa":"OFFSET gets slower as it grows and can skip/duplicate rows when data changes; a cursor seeks with an indexed `WHERE id > :last`","cat":"api"},{"id":"API-19","t":"m","l":2,"q":"Which REST constraint means each request carries all information needed to process it?","o":["Uniform interface","Statelessness","Cacheability","Layered system"],"a":1,"e":"Stateless: the server does not remember anything about the client between requests. Each request brings everything needed, e.g. an auth token.\nBenefit: any server instance can handle any request, so you can add servers behind a load balancer easily.\nUser data still lives in the database; 'stateless' refers to the server process memory.","r":"Stateless = every request is self-contained.","g":["stateless","rest","load_balancer","http","json","cookie","session"],"cat":"api"},{"id":"API-20","t":"m","l":3,"q":"A mobile app retries a payment POST after a timeout. How do you prevent a double charge?","o":["Use GET instead of POST for the payment requests of the app","Send an `Idempotency-Key` header; the server returns the first result","Disable all the retries in the mobile app after a timeout","Return a 500 error to the client on the second call"],"a":1,"e":"The timeout might have happened AFTER the server charged the card, so the client cannot know if the first try worked.\nThe client generates a unique key (a UUID) per payment attempt and sends it with every retry.\nThe server saves the key with the result. If the same key arrives again, it returns the saved result instead of charging again. Stripe's API works this way.","r":"Retries of POST → Idempotency-Key.","g":["idempotent","http_method","n_uuid","api"],"fa":"Have the client send an `Idempotency-Key` header; the server stores the key and returns the original result on repeats","cat":"api"},{"id":"API-21","t":"m","l":3,"q":"Which rate limiting algorithm naturally allows short bursts while enforcing an average rate?","o":["Fixed window counter","Token bucket","Round robin","FIFO queue"],"a":1,"e":"Picture a bucket that receives tokens at a fixed rate (e.g. 10 per second) up to a maximum (e.g. 50). Each request takes one token; no token, request rejected.\nIf a client was quiet, the bucket fills up, so it can send a short burst of 50 at once; over time it can never exceed 10 per second.\nFixed windows are simpler but allow double bursts at window edges.","r":"Token bucket = steady average + allowed bursts.","g":["rate_limit","n_token_bucket","status_code","n_retry_after"],"cat":"api"},{"id":"API-22","t":"m","l":3,"q":"What does gRPC typically offer over JSON/REST?","o":["Human-readable payloads that are easy to inspect by hand","Binary Protobuf over HTTP/2, strict contracts and streaming","Native browser support, without any proxy in between","No need for schemas, because messages describe themselves"],"a":1,"e":"gRPC defines services and messages in a `.proto` file and generates client and server code from it, so both sides share a strict contract.\nMessages are compact binary (Protobuf) over HTTP/2, which is fast and supports streaming in both directions.\nGreat for internal service-to-service calls. Downsides: not readable by humans, and browsers need a proxy (gRPC-Web).","r":"gRPC = fast, typed, binary; best between internal services.","g":["grpc","json","http2","http","rest"],"fa":"Binary Protobuf messages over HTTP/2, strict contracts and bidirectional streaming","cat":"api"},{"id":"API-23","t":"m","l":3,"q":"In GraphQL, resolving `posts { author { name } }` naively causes many DB queries. Common fix?","o":["Use REST endpoints instead of GraphQL for the nested data","Batch and cache the lookups per request with a DataLoader","Add more indexes to the tables of the database that is used","Disable the nested fields in the schema for all the clients"],"a":1,"e":"GraphQL calls a resolver function per field. For 50 posts, the `author` resolver runs 50 times = 50 queries (the N+1 problem again).\nA DataLoader collects all author IDs requested in the same moment and loads them in ONE query (`WHERE id IN (...)`), then hands each resolver its author.","r":"GraphQL N+1 → DataLoader batching.","g":["graphql","n_plus_1","join","cache","api","n_sql_clauses"],"fa":"Batch and cache per request with a DataLoader","cat":"api"},{"id":"API-24","t":"m","l":3,"q":"How should your service verify incoming webhooks from a provider?","o":["Check the User-Agent header that comes with the request","Verify an HMAC signature of the raw body, plus a timestamp","Only accept requests that arrive over a secure HTTPS connection","Trust any request that is sent to a secret, hard-to-guess URL"],"a":1,"e":"A webhook is the provider calling YOUR URL. Anyone on the internet could call that URL with fake data.\nThe provider signs each payload with a shared secret (HMAC). You recompute the signature over the raw body and compare (with `hmac.compare_digest`). If it matches, the data is genuine.\nAlso reject old timestamps (replayed messages) and handle duplicates, because providers retry.","r":"Webhooks: verify the HMAC signature, reject old timestamps.","g":["webhook","hmac","n_sha","header","http","endpoint"],"fa":"Verify an HMAC signature over the raw body with the shared secret, plus a timestamp to prevent replays","cat":"api"},{"id":"API-25","t":"m","l":2,"q":"An endpoint generates a 2-minute report. Best API design?","o":["Keep the HTTP request open for the full two minutes","Enqueue a job, return 202 Accepted with a status URL, then poll","Return a 500 error and ask the client to retry later","Use a GET request with a very large timeout on the client"],"a":1,"e":"Load balancers and proxies usually cut connections after 30-60 seconds, and a user staring at a spinner is bad UX.\nInstead: put the job in a queue, answer immediately with 202 Accepted and a URL like `/reports/123/status`. A background worker does the work.\nThe client checks the status URL (polling) or gets notified (webhook/WebSocket) when it is ready.","r":"Slow work → background job + 202 Accepted.","g":["background_job","message_queue","status_code","webhook","api","sqs_sns"],"fa":"Enqueue a job (Celery/RQ/SQS), return 202 Accepted with a status URL, let the client poll or receive a webhook","cat":"api"},{"id":"API-26","t":"m","l":3,"q":"A client sends `If-None-Match: \"abc123\"` and the resource is unchanged. Server response?","o":["200 OK with the full body of the resource","304 Not Modified with no body","204 No Content with no body","412 Precondition Failed with an error"],"a":1,"e":"An ETag is a version fingerprint the server sends with a response. The client stores it.\nNext time, the client sends `If-None-Match: <etag>`. If nothing changed, the server answers 304 Not Modified with an empty body, and the client reuses its cached copy. This saves bandwidth.\nFor updates, `If-Match` prevents overwriting someone else's change (412 if the version is old).","r":"Same ETag → 304, reuse the cache.","g":["etag","cache","header","status_code","http","idempotent"],"cat":"api"},{"id":"API-27","t":"m","l":3,"q":"A common starting point for the number of Gunicorn sync workers is…","o":["1 per server","(2 × CPU cores) + 1","100 per core","Equal to RAM in GB"],"a":1,"e":"Each sync worker handles one request at a time. More workers = more requests in parallel, but each uses memory and CPU.\nThe Gunicorn docs suggest (2 × cores) + 1 as a starting point (for 4 cores: 9 workers), then tune it with load tests.\nFor I/O-heavy apps, async workers (Uvicorn) or threads can handle many more connections.","r":"Start with 2 × cores + 1, then measure.","g":["worker","wsgi_asgi","n_cpu","load_test"],"cat":"api"},{"id":"API-28","t":"m","l":2,"q":"Which API versioning approach is most common and explicit in public REST APIs?","o":["Version in the URL path (`/v1/orders`)","Changing the field names silently","Using a different port per version","Never versioning the API at all"],"a":0,"e":"Clients integrate against your API and break if you change it. Versioning lets you release breaking changes as a new version while old clients keep working.\nPutting it in the path (`/v1/`, `/v2/`) is the most visible and common. Alternatives: a header or a query parameter.\nAnnounce deprecations early and keep old versions running for a while.","r":"Breaking API change → new version (/v2).","g":["versioning","rest","api","query_param"],"cat":"api"},{"id":"API-29","t":"f","l":2,"q":"Design a REST API for a bookings resource (hotel rooms). What endpoints, codes and concerns?","a":"- Resources: `GET /rooms?from=&to=` (availability), `POST /bookings` (201 + Location), `GET /bookings/{id}`, `PATCH /bookings/{id}` (change dates), `POST /bookings/{id}/cancel` or `DELETE` (200/204).\n- Errors: 400/422 validation, 401/403 auth, 404 missing, 409 conflict (room already booked), 429 rate limit.\n- Concurrency: prevent double booking with a DB constraint or a transaction with row lock / version check.\n- Idempotency-Key on POST; cursor pagination on lists; filter and sort parameters.\n- Auth (OAuth/JWT), ownership checks, consistent error format, versioning `/v1`, OpenAPI docs.","g":["rest","status_code","idempotent","pagination","http_method","transaction","api","jwt"],"cat":"api"},{"id":"API-30","t":"f","l":3,"q":"How would you secure a REST API end to end?","a":"- TLS everywhere; HSTS.\n- Authentication: OAuth 2.0/OIDC or short-lived JWT + refresh; validate signature, `exp`, `aud`, `iss`, allowed algorithms.\n- Authorization on every request at object level (prevent IDOR); least privilege, scopes/roles.\n- Validate input with schemas (Pydantic); parameterized queries; limit payload sizes.\n- Rate limiting and abuse detection; MFA and lockout for login.\n- Secrets in a secret manager; rotate keys.\n- Safe error messages (no stack traces), security headers, strict CORS.\n- Audit logs, dependency scanning, monitoring and alerts.","g":["https","jwt","authz","rate_limit","least_privilege","authn","oauth","rest"],"cat":"api"},{"id":"API-31","t":"m","l":1,"q":"What is an API?","o":["A programming language that is used to build servers","A defined way for one program to request data or actions from another","A type of database that stores the request logs of an app","A visual design tool that is used to draw interfaces"],"a":1,"e":"API means Application Programming Interface: the 'menu' a system offers to other programs. It lists what you can ask for and in what format, and hides how it works inside.\nA web API is reached over HTTP. Example: a weather app sends `GET https://api.weather.com/today?city=Lima` and receives JSON with the forecast.","r":"API = a contract for programs to talk to each other.","g":["api","http","json","interface","http_method"],"fa":"A defined way for one program to request data or actions from another, e.g. over HTTP","cat":"api"},{"id":"API-32","t":"m","l":1,"q":"Which list contains the main parts of an HTTP request?","o":["Method, URL, headers, optional body","Port, cookie, password, session id","HTML, CSS, JavaScript and images","Status code, reason phrase and body only"],"a":0,"e":"An HTTP request has:\n- Method: what to do (GET, POST, PUT, PATCH, DELETE).\n- URL: which resource (`/users/42`).\n- Headers: extra information (`Authorization`, `Content-Type`).\n- Body (optional): data you send, usually JSON, for POST/PUT/PATCH.\nThe RESPONSE has a status code, headers and a body.","r":"Request = method + URL + headers + body.","g":["http","http_method","header","z_url","status_code","authz"],"cat":"api"},{"id":"API-33","t":"m","l":1,"q":"What is the purpose of a GET request?","o":["Create a new resource on the server side","Retrieve data without changing anything","Delete data that is stored on the server","Upload files from the client to the server"],"a":1,"e":"GET asks the server for data. It must be 'safe': it should not create, change or delete anything.\nBecause of that, browsers, proxies and CDNs may cache and repeat GET requests freely.\nNever use GET for actions like `/delete-user?id=5`: a crawler or prefetch could trigger it.","r":"GET = read only.","g":["http_method","rest","endpoint","api","json"],"fa":"Retrieve data without changing anything on the server","cat":"api"},{"id":"API-34","t":"m","l":1,"q":"What do HTTP status codes starting with 2, 4 and 5 mean?","o":["2xx is an error, 4xx is success, 5xx is a redirect","2xx is success, 4xx is a client error, 5xx is a server error","All three groups mean that the request was a success","2xx is a redirect, 4xx is success, 5xx is a client error"],"a":1,"e":"The first digit tells the category:\n- 2xx: success (200 OK, 201 Created, 204 No Content).\n- 3xx: redirect (301, 302, 304).\n- 4xx: the client did something wrong (400 bad data, 401 not logged in, 403 forbidden, 404 not found).\n- 5xx: the server failed (500 bug, 502/503 server down or overloaded).","r":"2 = OK, 4 = your fault, 5 = server's fault.","g":["status_code","rest","header","json","http"],"fa":"2xx success, 4xx client error (your request is wrong), 5xx server error (the server failed)","cat":"api"},{"id":"API-35","t":"m","l":1,"q":"`GET /users/9999` and that user does not exist. Correct status code?","o":["200 with empty body","404 Not Found","500 Internal Server Error","401 Unauthorized"],"a":1,"e":"404 Not Found means the requested resource does not exist.\nReturning 200 with an empty body confuses clients, who think it worked. 500 would suggest the server crashed, which is not the case.","r":"Resource doesn't exist → 404.","g":["status_code","rest","endpoint","json","http_method"],"cat":"api"},{"id":"API-36","t":"m","l":1,"q":"Your API returns 500 Internal Server Error. What does that usually indicate?","o":["The user typed a wrong password when they tried to log in","An unexpected error in the server code, like an unhandled exception","The resource was not found at the URL that was requested","The request succeeded and the server returned the data"],"a":1,"e":"500 means the server failed in a way it did not expect: often an exception nobody caught (a bug), or a crashed dependency.\nThe client cannot fix it by changing the request. Check the server logs and the stack trace.\nGood APIs catch known problems and return a specific 4xx code instead.","r":"500 = bug or crash on the server. Check the logs.","g":["status_code","exception","api","z_server","dependency"],"fa":"An unexpected error in the server code, e.g. an unhandled exception","cat":"api"},{"id":"API-37","t":"m","l":1,"q":"What is JSON?","o":["A JavaScript framework that is used for building web apps","A lightweight text format for data, with `{}` objects and `[]` arrays","A database engine that stores documents as binary files","A binary image format that is commonly used on the web"],"a":1,"e":"JSON (JavaScript Object Notation) is plain text that both humans and programs read easily: `{\"name\": \"Ana\", \"skills\": [\"python\", \"sql\"]}`.\nIt is the most common format for API requests and responses.\nIn Python, `json.dumps(obj)` turns a dict into JSON text and `json.loads(text)` does the reverse.","r":"JSON = the text format APIs speak.","g":["json","javascript","object","array","n_json_loads","api"],"fa":"A lightweight text format for data, with objects `{}` and arrays `[]`","cat":"api"},{"id":"API-38","t":"m","l":1,"q":"In `GET /users/42/orders?status=paid&limit=10`, which are the path parameter and the query parameters?","o":["Path: status. Query: 42 and limit","Path: 42 (the user). Query: status and limit","Both are query parameters of the request","The URL does not contain any parameters"],"a":1,"e":"Path parameters are part of the URL path and usually identify a specific resource: `/users/42` → user 42.\nQuery parameters come after `?`, separated by `&`, and usually filter, sort or paginate: `status=paid`, `limit=10`.\nIn FastAPI: `def orders(user_id: int, status: str | None = None, limit: int = 10)`.","r":"Path = which resource. Query = how to filter it.","g":["path_param","query_param","http_method","z_url"],"fa":"Path: 42 (identifies the user); query: status and limit (filter/options)","cat":"api"},{"id":"API-39","t":"m","l":1,"q":"Which endpoint follows REST naming conventions?","o":["`POST /createUser`","`GET /getUserById?id=42`","`GET /users/42`","`GET /user_delete/42`"],"a":2,"e":"REST URLs name RESOURCES (nouns, usually plural), and the HTTP method says the action:\n- `GET /users/42` read user 42\n- `POST /users` create a user\n- `PATCH /users/42` update\n- `DELETE /users/42` delete\nPutting verbs in the URL (`/createUser`) repeats what the method already says.","r":"Nouns in the URL, verbs in the HTTP method.","g":["rest","http_method","http","z_url","endpoint"],"cat":"api"},{"id":"API-40","t":"m","l":1,"q":"What does HTTPS add to HTTP?","o":["Only faster page loads, mostly on slow mobile networks","Encryption and server identity checks via TLS, so data is safe","A different data format for the requests and the responses","Automatic login for the visitors that return to the site"],"a":1,"e":"With plain HTTP, anyone on the same Wi-Fi or network path can read and modify the traffic, including passwords.\nHTTPS wraps HTTP in TLS: the data is encrypted, protected against tampering, and the certificate proves you are talking to the real server.\nToday every site and API should use HTTPS.","r":"HTTPS = HTTP + encryption + identity check.","g":["https","tls","http","encryption","identity","api"],"fa":"Encryption and server identity verification via TLS, so data cannot be read or changed in transit","cat":"api"},{"id":"API-41","t":"m","l":1,"q":"What does the request header `Content-Type: application/json` tell the server?","o":["The client wants JSON back in the response","The body of this request is formatted as JSON","The request is encrypted before it is sent","The user is already logged in"],"a":1,"e":"`Content-Type` describes the format of the body being SENT. With `application/json` the server knows to parse the body as JSON.\nTo say which format you want BACK, the client uses the `Accept` header.\nIf the header is wrong or missing, many frameworks reject or misread the body.","r":"Content-Type = format of what I send. Accept = format I want back.","g":["header","json","n_content_type","z_server","z_framework"],"cat":"api"},{"id":"API-42","t":"m","l":1,"q":"In FastAPI, what does `@app.get(\"/items/{item_id}\")` above a function do?","o":["It downloads an item from the server to the client","It registers a GET route; `item_id` is taken from the URL","It creates a database table named items for the function","It defines a test case for the function underneath it"],"a":1,"e":"Routing connects a URL + HTTP method to a Python function (an endpoint).\nWhen a request `GET /items/7` arrives, FastAPI calls your function with `item_id=7`, converting it to the type you declared (e.g. int).\nWhatever the function returns (dict, Pydantic model) is turned into the JSON response.","ec":"@app.get(\"/items/{item_id}\")\ndef read_item(item_id: int):\n    return {\"id\": item_id}","r":"Route = method + path → function.","g":["routing","endpoint","path_param","http_method","z_url","http"],"fa":"Registers a route: GET requests to /items/<id> are handled by that function, with item_id taken from the URL","cat":"api"},{"id":"API-43","t":"m","l":0,"q":"What is the backend of a web application?","o":["The server part: business logic, data access and security","The visual design of the pages that the users see","The browser in which the user opens the application","Only the database in which the data is stored"],"a":0,"e":"The backend is the code and systems running on servers.\nIt receives requests from the frontend, applies the rules of the business (for example 'a user cannot buy more items than the stock'), reads or writes the database, checks who is logged in, and sends back a response.\nTypical backend technologies: Java with Spring Boot, Python with FastAPI or Django, Node.js.","r":"Backend = server-side logic, data and security.","g":["z_backend","z_frontend","z_database","sp_spring_boot","z_server","z_nodejs"],"fa":"The part on servers that holds the business logic, talks to the database and checks security; users never see it directly","cat":"api"},{"id":"API-44","t":"m","l":0,"q":"What is a server?","o":["A very expensive computer that only large companies can own","A computer or program that waits for requests and sends responses","A type of database that is used to store the user data","A programming language that is used mainly for backends"],"a":1,"e":"The word has two meanings and both are used.\nHardware: a computer connected to a network that stores files and runs programs for others.\nSoftware: a program that listens for requests (for example a web server that understands HTTP) and answers them.\nA server can be your laptop while you develop, or a machine in a cloud data center in production.","r":"Server = waits for requests and answers them.","g":["z_server","client_server","api","z_url","z_backend","http"],"fa":"A computer or program that waits for requests from clients and sends back responses","cat":"api"},{"id":"API-45","t":"m","l":0,"q":"In 'client and server', what is a client?","o":["The person who pays for the software that is being built","Whoever starts a request: a browser, an app or another program","The database in which the data of the system is stored","The operating system that runs on the server machine"],"a":1,"e":"The client asks, the server answers.\nYour browser is a client when it requests a web page. A mobile app is a client when it asks the backend for your orders. A backend can also be a client of another service.\nIn HTTP, the client always starts the conversation and the server answers.","r":"Client = the one who sends the request.","g":["client_server","z_server","z_backend","http"],"fa":"Whoever starts a request: a browser, a phone app, or even another program","cat":"api"},{"id":"API-46","t":"m","l":0,"q":"What does 'full-stack developer' mean?","o":["Someone who works only on databases and on their queries","Someone who works on both the frontend and the backend","Someone who has a full-time contract with a company","Someone who knows every programming language that exists"],"a":1,"e":"The 'stack' is the set of technology layers an application is made of: frontend, backend, database, and infrastructure.\nA full-stack developer is comfortable across those layers. It does not mean an expert in all of them, but able to build a feature end to end.\nExample stack: React (frontend) + Spring Boot (backend) + PostgreSQL (database).","r":"Full-stack = frontend + backend.","g":["z_stack","z_frontend","z_backend","z_database","sp_spring_boot","react"],"fa":"Someone who can work on both the frontend and the backend (and usually the database and deployment basics)","cat":"api"},{"id":"API-47","t":"m","l":0,"q":"Restaurant analogy: the customer orders from a waiter, who takes the order to the kitchen and brings back the food. Which part is the API?","o":["The customer, who makes the order and waits for the food","The waiter: the agreed way to ask the kitchen and get an answer","The kitchen, where the food is made and then served","The price list, which the customer reads before ordering"],"a":1,"e":"An API (Application Programming Interface) is a contract about how programs talk to each other.\n- Customer = the client app (browser, mobile app).\n- Waiter = the API: you order using the menu (the documented requests), and you get a response.\n- Kitchen = the backend that does the real work.\nThe customer does not need to know how the kitchen works, only how to order.","r":"API = the waiter between client and backend.","g":["api","z_backend","client_server","http","json","rest"],"fa":"The waiter: the agreed way to ask the kitchen for something and get an answer, without entering the kitchen","cat":"api"},{"id":"API-48","t":"m","l":0,"q":"What is HTTP?","o":["A programming language that is used for building web pages","The protocol browsers and servers use: a request, then a response","A type of database that is used for storing web data","An antivirus program that scans the traffic of the web"],"a":1,"e":"HTTP (HyperText Transfer Protocol) is the language of the web. A request has a method (like GET), a path and optional headers and body. A response has a status code (like 200 or 404), headers and usually a body.\nIt is a client-server protocol: the client always starts the conversation.\nHTTPS is HTTP inside an encrypted connection.","r":"HTTP = how clients and servers talk on the web.","g":["http","https","status_code","z_server","http_method"],"fa":"The set of rules (protocol) that browsers and servers use to exchange web pages and data: a client sends a request and the server sends a response","cat":"api"},{"id":"API-49","t":"m","l":0,"q":"In the address `https://api.shop.com/products?id=7`, which part is the path?","o":["https","api.shop.com","/products","id=7"],"a":2,"e":"A URL is made of parts:\n- `https` is the scheme (protocol).\n- `api.shop.com` is the host (the server's domain name).\n- `/products` is the path (which resource on that server).\n- `?id=7` is the query string (extra parameters).\nThe port is hidden: HTTPS uses 443 by default and HTTP uses 80.","r":"URL = scheme + host + path + query.","g":["z_url","path_param","query_param","z_server","https","http"],"cat":"api"},{"id":"API-50","t":"m","l":0,"q":"Which sentence best describes REST?","o":["A database engine that is designed for storing web data","A style for web APIs: resources with URLs, acted on by HTTP methods","A security protocol that is used for logins and sessions","A JavaScript framework that is used for building frontends"],"a":1,"e":"REST (Representational State Transfer) is an architectural style described by Roy Fielding in his doctoral dissertation (2000). It is not a library or a protocol.\nIn practice: `GET /users/42` reads user 42, `POST /users` creates one, `DELETE /users/42` removes it.\nIts constraints include client-server, stateless requests, cacheable responses and a uniform interface.","r":"REST = resources + URLs + HTTP methods.","g":["rest","http_method","http","interface","stateless"],"fa":"A style for designing web APIs: things are resources with URLs, and the standard HTTP methods (GET, POST, PUT, DELETE) act on them","cat":"api"},{"id":"API-51","t":"m","l":0,"q":"What does a backend web framework such as Spring Boot, FastAPI or Django do for you?","o":["It gives ready-made blocks: routing, JSON and database access","It replaces the need for a database in the application","It designs the screens and the pages that users will see","It makes the physical server faster by tuning the hardware"],"a":0,"e":"Without a framework you would write by hand how to read network requests, parse data and match URLs.\nA framework solves those repeated problems so you write only your own logic.\nExample: in Spring Boot you write a method and mark it with `@GetMapping(\"/hello\")`, and the framework calls it when someone visits `/hello`.","r":"Framework = reusable foundation for server code.","g":["z_framework","endpoint","sp_spring_boot","z_backend","json"],"fa":"It provides ready-made building blocks for common server tasks: receiving requests, routing URLs to your code, reading JSON, talking to databases","cat":"api"},{"id":"API-52","t":"m","l":0,"q":"In an HTTP conversation, who sends the first message?","o":["The server, with a welcome message","The client, with a request","Both of them at the same time","The database, with a query"],"a":1,"e":"HTTP always works as request then response.\nThe client (usually a browser or app) sends the request, and the server answers. A server does not normally start sending to a client by itself.\nFor live updates (chat, notifications) there are other mechanisms such as WebSockets.","r":"Client asks first, server answers.","g":["http","websocket","client_server","header","status_code","api"],"cat":"api"},{"id":"DB-01","t":"m","l":2,"q":"What is the main cost of adding an index to a table?","o":["Slower SELECT queries on the column that is indexed","Extra storage and slower writes, since the index must be updated","The table is locked permanently after the index is created","Foreign keys are disabled on the table that is indexed"],"a":1,"e":"An index is an extra sorted structure (usually a B-tree) that lets the database find rows quickly, like the index at the back of a book.\nBut every time you insert, update or delete a row, every index on that table must be updated too, and indexes take disk space.\nSo index the columns your important queries filter, join or sort on, not every column.","r":"Indexes speed up reads and slow down writes.","g":["index","b_tree","primary_key","composite_index","table"],"fa":"Extra storage and slower INSERT/UPDATE/DELETE because the index must be maintained","cat":"db"},{"id":"DB-02","t":"m","l":2,"q":"Table has a composite index on `(last_name, first_name)`. Which query can use it efficiently?","o":["WHERE first_name = 'Ana'","WHERE last_name = 'Ruiz'","WHERE first_name LIKE '%a'","None of them"],"a":1,"e":"A composite index is sorted by the first column, then by the second inside each first value, like a phone book sorted by surname, then first name.\nYou can quickly find everyone named Ruiz, or Ruiz + Ana. But finding every 'Ana' regardless of surname means scanning the whole book.\nThis is the leftmost-prefix rule: the index helps only if you filter on its first column(s).","r":"Composite index works left to right.","g":["composite_index","index","sql","table","explain","n_sql_clauses"],"cat":"db"},{"id":"DB-03","t":"m","l":2,"q":"In ACID, what does Isolation guarantee?","o":["Data survives crashes and power failures","Concurrent transactions behave as if run in some serial order","Transactions are all-or-nothing, never partially applied","Constraints are always satisfied after each transaction"],"a":1,"e":"ACID are four guarantees of database transactions:\n- Atomicity: all or nothing.\n- Consistency: rules and constraints always hold.\n- Isolation: transactions running at the same time do not see each other's half-finished work.\n- Durability: once committed, data survives a crash.\nIsolation has levels: stricter levels are safer but slower.","r":"Isolation = concurrent transactions don't step on each other.","g":["acid","transaction","isolation_level","deadlock","optimistic_locking","pessimistic_locking","lock"],"fa":"Concurrent transactions behave as if executed in some serial order (to the degree of the chosen isolation level)","cat":"db"},{"id":"DB-04","t":"m","l":3,"q":"In the SQL standard, which is the lowest isolation level that prevents non-repeatable reads?","o":["Read Uncommitted","Read Committed","Repeatable Read","Serializable"],"a":2,"e":"A non-repeatable read: inside one transaction you read a row twice and get different values, because another transaction changed and committed it in between.\nLevels, from weakest to strongest:\n- Read Uncommitted: can see uncommitted data (dirty reads).\n- Read Committed: no dirty reads (PostgreSQL default).\n- Repeatable Read: also no non-repeatable reads.\n- Serializable: also no phantoms (new matching rows appearing).","r":"Read Committed < Repeatable Read < Serializable.","g":["isolation_level","transaction","acid","deadlock","lock","table"],"cat":"db"},{"id":"DB-05","t":"m","l":1,"q":"`customers LEFT JOIN orders ON ...` returns…","o":["Only the customers who have at least one order in the table","All customers; order columns are NULL when there is no order","All orders; customer columns are NULL when a customer is missing","The Cartesian product of both the tables, with all the pairs"],"a":1,"e":"An INNER JOIN keeps only rows that have a match on both sides.\nA LEFT JOIN keeps EVERY row from the left table (customers). When a customer has no orders, the order columns are filled with NULL.\nUseful for 'show all customers, with their orders if any', or to find customers with no orders: `WHERE orders.id IS NULL`.","r":"LEFT JOIN keeps all left rows; missing matches become NULL.","g":["left_join","join","null","inner_join","n_null_compare","n_sql_clauses"],"fa":"All customers; order columns are NULL for customers without orders","cat":"db"},{"id":"DB-06","t":"m","l":1,"q":"What is the difference between WHERE and HAVING?","o":["There is no difference between them, apart from their names","WHERE filters rows before grouping; HAVING filters the groups","HAVING is always faster than WHERE in every database","WHERE works only together with JOINs in a query"],"a":1,"e":"SQL runs WHERE first: it removes individual rows. Then GROUP BY makes groups and aggregates (COUNT, SUM...). Then HAVING filters the groups using those aggregate results.\nExample: departments with more than 5 active employees.","ec":"SELECT dept, COUNT(*)\nFROM employees\nWHERE active = true          -- filter rows\nGROUP BY dept\nHAVING COUNT(*) > 5;         -- filter groups","r":"WHERE filters rows, HAVING filters groups.","g":["group_by","aggregate","n_sql_clauses","n_count","sql"],"fa":"WHERE filters rows before grouping; HAVING filters groups after aggregation","cat":"db"},{"id":"DB-07","t":"m","l":2,"q":"Which query returns the second highest distinct salary?","o":["SELECT salary FROM emp ORDER BY salary DESC LIMIT 2 (returns two rows)","SELECT MAX(salary) FROM emp WHERE salary < (SELECT MAX(salary) FROM emp)","SELECT MIN(salary) FROM emp WHERE salary > (SELECT AVG(salary) FROM emp)","SELECT salary FROM emp WHERE rank = 2 ORDER BY salary DESC"],"a":1,"e":"The inner query finds the highest salary. The outer query finds the highest salary that is LOWER than that, which is the second highest.\nThe option with LIMIT 2 returns two rows (the two highest salaries), not just the second one.\nAlternative: `DENSE_RANK() OVER (ORDER BY salary DESC)` and keep rank 2. In interviews, ask how ties should be handled.","r":"Second highest = MAX below the MAX.","g":["aggregate","window_function","sql","n_distinct","join","table"],"cat":"db"},{"id":"DB-08","t":"m","l":2,"q":"`COUNT(*)` vs `COUNT(email)`?","o":["They are identical and always return the same number","`COUNT(*)` counts all rows; `COUNT(email)` skips NULL emails","`COUNT(email)` counts only the distinct emails","`COUNT(*)` skips rows that contain any NULL"],"a":1,"e":"`COUNT(*)` counts rows, no matter what they contain.\n`COUNT(email)` counts only rows where email has a value (not NULL). Most aggregate functions (SUM, AVG, COUNT(column)) ignore NULLs.\nFor unique values: `COUNT(DISTINCT email)`.","r":"COUNT(column) ignores NULLs.","g":["aggregate","null","n_count","sql","table","group_by"],"fa":"`COUNT(*)` counts all rows; `COUNT(email)` skips rows where email is NULL","cat":"db"},{"id":"DB-09","t":"m","l":1,"q":"What does `SELECT * FROM users WHERE deleted_at = NULL` return?","o":["Users with deleted_at NULL","No rows","All rows","An error in all databases"],"a":1,"e":"NULL means 'unknown'. Comparing anything with unknown gives unknown, even NULL = NULL. WHERE keeps only rows where the condition is TRUE, so no rows match.\nThe correct way is `WHERE deleted_at IS NULL` (or `IS NOT NULL`).","r":"Use IS NULL, never = NULL.","g":["null","sql","n_null_compare","table","z_query","n_sql_clauses"],"cat":"db"},{"id":"DB-10","t":"m","l":2,"q":"Why might you deliberately denormalize a schema?","o":["To remove all the redundancy that exists in the schema","To speed up reads by avoiding joins, with duplicated data","To enforce the constraints of the schema more strictly","Because normalization is deprecated in modern databases"],"a":1,"e":"Normalization splits data so each fact is stored once (no duplicates), which keeps updates simple and consistent.\nDenormalization deliberately copies some data (e.g. storing `comment_count` on the post, or the customer name on the order) so frequent reads avoid joins and are faster.\nThe cost: you must keep the copies in sync when data changes.","r":"Denormalize = duplicate data on purpose for faster reads.","g":["normalization","denormalization","join","index","table","schema","d_normal_forms"],"fa":"To speed up read-heavy queries by avoiding joins, accepting duplicated data and harder updates","cat":"db"},{"id":"DB-11","t":"m","l":3,"q":"How do you get the top-paid employee per department in one query?","o":["GROUP BY dept and use MAX(name) to pick the top employee","ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC), keep 1","ORDER BY dept, salary DESC and then add LIMIT 1 to the query","SELECT DISTINCT dept and add the highest salary to the result"],"a":1,"e":"A window function calculates a value for each row by looking at a group of related rows (the 'window'), without merging rows like GROUP BY does.\nPARTITION BY dept restarts numbering in each department; ORDER BY salary DESC puts the highest first, so row number 1 is the top earner.\nUse RANK() instead if ties should all be returned.","ec":"SELECT * FROM (\n  SELECT name, dept, salary,\n         ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn\n  FROM employees\n) t\nWHERE rn = 1;","r":"Top N per group → ROW_NUMBER() OVER (PARTITION BY ...).","g":["window_function","n_sql_clauses","sql","table","join","group_by"],"fa":"ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) and keep rn = 1","cat":"db"},{"id":"DB-12","t":"m","l":3,"q":"Two transactions lock rows A then B, and B then A, and deadlock. Best prevention?","o":["Increase the lock timeouts of the database to wait longer","Take locks in the same order everywhere and keep transactions short","Disable transactions in the application for these operations","Use SELECT * so that all the columns of the rows are locked"],"a":1,"e":"Deadlock: transaction 1 holds A and waits for B, while transaction 2 holds B and waits for A. Both wait forever, so the database kills one of them.\nIf every piece of code always locks rows in the same order (e.g. lowest ID first), this circle cannot form.\nShort transactions hold locks for less time. Also retry when the database reports a deadlock.","r":"Same lock order everywhere → no deadlocks.","g":["deadlock","lock","transaction","isolation_level","acid","n_lock_order"],"fa":"Acquire locks in a consistent order everywhere and keep transactions short","cat":"db"},{"id":"DB-13","t":"m","l":3,"q":"Optimistic locking is typically implemented with…","o":["`SELECT ... FOR UPDATE` on the row you want to change","A version column, updated only when `version` still matches","Table locks taken at the start of every transaction","A cron job that checks for conflicts every minute"],"a":1,"e":"Optimistic locking assumes conflicts are rare and does not lock anything while you read.\nEach row has a `version` number. When saving, you update only if the version is still the one you read, and increase it.\nIf 0 rows were updated, someone else saved first: reload and retry, or show a conflict message.\nPessimistic locking (`SELECT ... FOR UPDATE`) locks the row up front instead.","r":"Optimistic = check a version number when saving.","g":["optimistic_locking","pessimistic_locking","transaction","acid","sql","n_sql_clauses"],"fa":"A version column: `UPDATE ... SET version = version + 1 WHERE id = ? AND version = ?` and checking affected rows","cat":"db"},{"id":"DB-14","t":"m","l":2,"q":"Which scenario most favors a document store (e.g. MongoDB) over a relational DB?","o":["A banking ledger with strict multi-table transactions","Flexible nested records read as a whole, with varying schema","Heavy ad-hoc reporting that joins many tables","Strong referential integrity between entities"],"a":1,"e":"Relational databases (PostgreSQL, MySQL) shine with structured data, joins between tables, constraints and transactions.\nDocument stores keep each record as a JSON-like document, good when data is naturally nested, read as one piece, and its shape varies (e.g. product catalogs with different attributes per category).\nMany companies use both.","r":"Relational for relations and transactions; documents for flexible nested data.","g":["nosql","schema","transaction","d_relational","json"],"fa":"Flexible, nested per-record data read as a whole, with schema varying across records","cat":"db"},{"id":"DB-15","t":"m","l":2,"q":"Replication vs sharding: which statement is correct?","o":["Both split the data across nodes, using the same technique","Replication copies data to nodes; sharding splits data across them","Sharding is only used for caching the results of queries","Replication improves write throughput in a linear way"],"a":1,"e":"Replication: several servers hold a COPY of the same data. If one dies, another takes over, and reads can be spread across copies.\nSharding: data is SPLIT; each server holds a different part (e.g. users A-M on one, N-Z on another). This scales writes and storage.\nSharding needs a good shard key and makes queries across shards harder.","r":"Replication = copies. Sharding = pieces.","g":["replication","sharding","availability","high_availability","failover","consistency"],"fa":"Replication copies the same data to several nodes (read scaling, availability); sharding partitions data across nodes (write and storage scaling)","cat":"db"},{"id":"DB-16","t":"m","l":3,"q":"A user updates their profile, refreshes, and sees the old data. Reads go to async read replicas. What is happening?","o":["A cache stampede that happens on the key of the profile","Replication lag; send that user's reads to the primary for a while","A deadlock between two updates of the profile of the user","Corruption in the index of the table that stores the users"],"a":1,"e":"With asynchronous replication, the primary database confirms the write immediately and sends it to the replicas a moment later.\nIf the next read hits a replica that has not received the change yet, the user sees old data. This delay is replication lag (eventual consistency).\nFix: after a user writes, send that user's reads to the primary for a short time.","r":"Async replicas can be slightly behind the primary.","g":["read_replica","replication","eventual_consistency","failover","latency","consistency","cache"],"fa":"Replication lag; fix with read-your-writes (route the user's reads to the primary briefly)","cat":"db"},{"id":"DB-17","t":"m","l":2,"q":"`EXPLAIN` shows a sequential scan on a 50M-row table for `WHERE email = ?`. Most likely fix?","o":["Add more RAM","Add an index on `email`","Rewrite in NoSQL","Use SELECT DISTINCT"],"a":1,"e":"EXPLAIN shows the plan the database will use for a query. A 'sequential scan' means it reads every row, here all 50 million, to find one email.\nAn index on `email` lets it jump directly to the matching row.\nUse `EXPLAIN ANALYZE` to see real times, and watch out for functions like `LOWER(email)`, which need an index on that expression.","r":"Seq scan on a big table + selective filter → add an index.","g":["explain","index","sql","table","d_covering_index","time_complexity"],"cat":"db"},{"id":"DB-18","t":"m","l":2,"q":"UNION vs UNION ALL?","o":["They are identical in the result and in the speed of the query","UNION removes duplicates; UNION ALL keeps every row and is faster","UNION ALL removes duplicates; UNION keeps every row of both","UNION only works when both of the queries use the same table"],"a":1,"e":"Both stack the results of two queries on top of each other.\nUNION then removes duplicate rows, which requires extra work (sorting or hashing).\nUNION ALL keeps everything and is faster. Use it when duplicates are impossible or acceptable.","r":"Prefer UNION ALL unless you need to remove duplicates.","g":["union","sql","sorting","aggregate"],"fa":"UNION removes duplicates (extra sort/hash cost); UNION ALL keeps all rows and is faster","cat":"db"},{"id":"DB-19","t":"m","l":1,"q":"Which is true about a PRIMARY KEY vs a UNIQUE constraint?","o":["Both of them allow multiple NULLs in the constrained column","One primary key per table (NOT NULL); many UNIQUE constraints","A UNIQUE constraint never creates an index in the table","Primary keys must always be integers, never text or UUIDs"],"a":1,"e":"The primary key is THE identifier of each row: unique and never NULL, and a table has only one.\nA UNIQUE constraint just forbids duplicate values in a column (like `email`). You can have several, and they usually allow NULL.\nBoth create an index automatically. Primary keys can be integers, UUIDs or other types.","r":"One primary key per table; many UNIQUE constraints allowed.","g":["primary_key","unique_constraint","null","n_uuid","table"],"fa":"A table has one primary key (NOT NULL, unique); it can have many UNIQUE constraints, which usually allow NULLs","cat":"db"},{"id":"DB-20","t":"m","l":2,"q":"Which is NOT a typical Redis use case?","o":["Caching the data that is read very frequently","Counters that are used for rate limiting","Storing the sessions of the users","Primary store for complex relational reports"],"a":3,"e":"Redis is an extremely fast in-memory key-value store with useful data types (strings, lists, sets, sorted sets, hashes).\nTypical uses: cache, counters for rate limiting, sessions, queues, leaderboards, distributed locks.\nIt is not designed for complex queries, joins and reports; that is the job of a relational database or data warehouse.","r":"Redis = fast memory store for cache, counters, sessions, queues.","g":["redis","cache","rate_limit","d_relational"],"fa":"Primary store for complex relational reporting","cat":"db"},{"id":"DB-21","t":"m","l":2,"q":"Why use a database connection pool?","o":["To encrypt the queries that are sent from the app to the database","Opening connections is costly; a pool reuses a limited set of them","To split the data of the application across several servers","To cache the results of queries that are repeated often"],"a":1,"e":"Opening a database connection takes time (network handshake, authentication) and each open connection uses memory on the database server.\nA pool keeps a fixed number of connections open and lends them to requests, which return them when done.\nSize it so that all app instances together stay under the database's max connections.","r":"Reuse connections with a pool; don't open one per query.","g":["connection_pool","latency","sql","z_database","throughput","authn"],"fa":"Opening connections is expensive; a pool reuses a bounded set and protects the DB from too many connections","cat":"db"},{"id":"DB-22","t":"m","l":1,"q":"Why are parameterized queries preferred over string formatting?","c":"cur.execute(f\"SELECT * FROM users WHERE name = '{name}'\")   # A\ncur.execute(\"SELECT * FROM users WHERE name = %s\", (name,))  # B","o":["A is faster, because it skips the handling of the parameters","B prevents SQL injection, as values travel apart from the SQL text","They are equivalent in safety and also in behavior","B only works in SQLite and not in the other databases"],"a":1,"e":"In A, user input becomes part of the SQL code. If `name` is `' OR '1'='1`, the query returns every user. That attack is SQL injection.\nIn B, the SQL and the value travel separately; the database always treats `name` as data, never as code.\nNever build SQL with f-strings from user input.","r":"Always pass values as parameters, never inside the SQL string.","g":["sql_injection","sql","n_sql_clauses","z_database"],"fa":"B prevents SQL injection because values are sent separately from the SQL text","cat":"db"},{"id":"DB-23","t":"f","l":3,"q":"A query became slow in production. How do you investigate?","a":"- Confirm and measure: which query, how slow, since when (slow query log, `pg_stat_statements`, APM traces).\n- Reproduce with `EXPLAIN ANALYZE`; look for sequential scans, wrong row estimates, expensive sorts, nested loops over big sets.\n- Check recent changes: deploys, data growth, new filters, outdated statistics (`ANALYZE`).\n- Fixes: add or adjust indexes (composite, covering, partial), rewrite the query, avoid N+1, paginate, cache, denormalize or add a read replica.\n- Check locks and connection pool saturation.\n- Verify the fix with the same measurement and add monitoring.","g":["explain","index","n_plus_1","connection_pool","read_replica"],"cat":"db"},{"id":"DB-24","t":"f","l":2,"q":"Design the schema for a simple e-commerce store (customers, products, orders).","a":"- `customers(id PK, email UNIQUE, name, created_at)`\n- `products(id PK, sku UNIQUE, name, price_cents, stock)`\n- `orders(id PK, customer_id FK, status, total_cents, created_at)`\n- `order_items(order_id FK, product_id FK, quantity, unit_price_cents, PK(order_id, product_id))`: copy the price at purchase time.\n- Money as integer cents or DECIMAL, never float.\n- Indexes: `orders(customer_id, created_at)` and the foreign keys.\n- Decrement stock in a transaction with a check (`UPDATE ... WHERE stock >= qty`) to avoid overselling.\n- Mention soft deletes, timestamps, and status as an enum/state machine.","g":["primary_key","foreign_key","normalization","transaction","unique_constraint","n_sql_clauses"],"cat":"db"},{"id":"DB-25","t":"m","l":1,"q":"What is a primary key?","o":["The first column of every table that is created in a database","A column (or columns) that uniquely identifies each row, never NULL","The password that is used to protect access to the database","The most important table of the whole schema of the database"],"a":1,"e":"Each row needs a unique ID so you can point to exactly that row: update it, delete it, or reference it from another table.\nTypical primary keys: an auto-increment integer `id` or a UUID.\nThe database guarantees no two rows share the same primary key value.","r":"Primary key = unique ID of each row.","g":["primary_key","table","null","z_database","n_uuid"],"fa":"A column (or set of columns) that uniquely identifies each row and can never be NULL","cat":"db"},{"id":"DB-26","t":"m","l":1,"q":"`orders.customer_id` references `customers.id`. What is `customer_id`?","o":["A primary key of the orders table that identifies each order","A foreign key that links each order to a customer row","The name of an index that was created on the orders table","A duplicate column that should be deleted from the table"],"a":1,"e":"A foreign key is a column that stores the primary key of a row in another table, creating a relationship: each order belongs to one customer.\nThe database can enforce it: you cannot create an order for a customer that does not exist, or delete a customer who still has orders (unless you configure cascade).","r":"Foreign key = link to a row in another table.","g":["foreign_key","primary_key","table","z_database"],"fa":"A foreign key: it links each order to a row in another table","cat":"db"},{"id":"DB-27","t":"m","l":1,"q":"Which query returns the names of users older than 30?","o":["SELECT name FROM users WHERE age > 30;","SELECT users WHERE age > 30;","GET name FROM users IF age > 30;","SELECT * FROM users HAVING age > 30 ORDER;"],"a":0,"e":"Basic SQL shape: `SELECT columns FROM table WHERE condition;`\n- SELECT name: which columns to return (`*` = all).\n- FROM users: which table.\n- WHERE age > 30: keep only rows matching the condition.\nKeywords are usually written in UPPERCASE for readability, but SQL does not require it.","r":"SELECT what FROM where WHERE condition.","g":["sql","table","n_sql_clauses","z_query","z_database"],"cat":"db"},{"id":"DB-28","t":"m","l":1,"q":"How do you get the 5 most expensive products?","o":["SELECT * FROM products ORDER BY price LIMIT 5;","SELECT * FROM products ORDER BY price DESC LIMIT 5;","SELECT TOP price FROM products;","SELECT * FROM products WHERE price = MAX;"],"a":1,"e":"`ORDER BY price` sorts from smallest to largest by default (ASC). Adding `DESC` sorts from largest to smallest.\n`LIMIT 5` keeps only the first 5 rows of that sorted result.\nWithout `DESC` you would get the 5 CHEAPEST products.","r":"ORDER BY ... DESC LIMIT n = top n.","g":["sql","sorting","z_query","table","n_sql_clauses"],"cat":"db"},{"id":"DB-29","t":"m","l":1,"q":"Which query counts users per country?","o":["SELECT country, COUNT(*) FROM users GROUP BY country;","SELECT COUNT(country) FROM users GROUP BY *;","SELECT country FROM users COUNT BY country;","SELECT * FROM users GROUP BY COUNT(country);"],"a":0,"e":"GROUP BY country puts rows with the same country together into groups.\nCOUNT(*) then counts the rows inside each group.\nThe result has one row per country, e.g. ('Peru', 120), ('Spain', 85).","r":"GROUP BY + COUNT = counts per category.","g":["group_by","aggregate","z_query","table","sql","n_count"],"cat":"db"},{"id":"DB-30","t":"m","l":1,"q":"What does an INNER JOIN between `orders` and `customers` on `orders.customer_id = customers.id` return?","o":["Every order and every customer, whether they match or not","Only orders that have a matching customer, with columns of both","Only the customers, without any of the data from the orders","Only the number of orders that exist in the orders table"],"a":1,"e":"A JOIN combines rows from two tables using a matching rule, so you can see order data and customer data in the same row.\nINNER JOIN keeps only pairs that match on both sides. Orders without a customer, or customers without orders, are left out.\nUse LEFT JOIN when you want to keep all rows from the first table.","ec":"SELECT orders.id, customers.name\nFROM orders\nINNER JOIN customers ON orders.customer_id = customers.id;","r":"INNER JOIN = only matching pairs.","g":["inner_join","join","table","left_join","n_sql_clauses"],"fa":"Only the rows where an order has a matching customer, combining columns from both tables","cat":"db"},{"id":"DB-31","t":"m","l":1,"q":"What happens when you run `DELETE FROM users;` without a WHERE clause?","o":["Nothing, WHERE is required","It deletes ALL rows in the table","It deletes the table structure","It deletes the first row"],"a":1,"e":"Without WHERE, the statement applies to every row: all users are deleted (the empty table remains).\nSame danger with `UPDATE users SET ...` without WHERE: every row changes.\nGood habits: write the WHERE first, run a SELECT with the same WHERE to check, and work inside a transaction you can roll back.","r":"DELETE/UPDATE without WHERE affects every row.","g":["sql","transaction","n_sql_clauses","table"],"cat":"db"},{"id":"DB-32","t":"m","l":1,"q":"A bank transfer subtracts money from A and adds it to B. Why run both in one transaction?","o":["To make both of the updates run faster on the database server","Both changes happen together or neither does, so no money is lost","Transactions encrypt the data during the transfer of money","To lock the whole bank database while the update is running"],"a":1,"e":"A transaction groups several statements into one all-or-nothing unit (atomicity).\nIf the system crashes after subtracting from A but before adding to B, the database rolls back the whole transaction, so A keeps the money.\nYou start it with BEGIN, finish with COMMIT, or undo with ROLLBACK.","ec":"BEGIN;\nUPDATE accounts SET balance = balance - 100 WHERE id = 'A';\nUPDATE accounts SET balance = balance + 100 WHERE id = 'B';\nCOMMIT;","r":"Transaction = all or nothing.","g":["transaction","acid","n_sql_clauses","rollback","git_commit"],"fa":"So both changes happen together or neither happens; a crash in the middle cannot lose money","cat":"db"},{"id":"DB-33","t":"m","l":1,"q":"Which statement best describes SQL vs NoSQL databases?","o":["NoSQL means a kind of database that holds no data at all","SQL uses tables with a fixed schema and joins; NoSQL uses flexible models","SQL is always faster than NoSQL, whatever the workload is","NoSQL databases cannot store JSON documents or nested data"],"a":1,"e":"SQL (relational) databases such as PostgreSQL and MySQL use tables with defined columns, relationships through keys, joins and strong transactions.\nNoSQL is a family of other models: document stores (MongoDB), key-value (Redis, DynamoDB), wide-column (Cassandra), graph (Neo4j). They often trade some features for flexibility or horizontal scale.\nFor most business apps, a relational database is the safe default.","r":"Relational = tables + joins + transactions. NoSQL = other data models.","g":["sql","nosql","schema","transaction","d_relational","o_rds_dynamo"],"fa":"SQL databases store data in tables with a fixed schema and support joins; NoSQL covers other models (documents, key-value, wide-column, graph) with more flexible schemas","cat":"db"},{"id":"DB-34","t":"m","l":1,"q":"What is a database index, in simple terms?","o":["A backup copy of the table that is kept in the same database","A lookup structure that finds rows without reading the whole table","The row number of each record in the table, starting from one","A list of the users who have access to the database tables"],"a":1,"e":"Without an index, finding `email = 'ana@x.com'` means checking every row, one by one (a full scan).\nAn index keeps the values sorted with pointers to the rows, so the database can jump straight to the right place, like using the index at the back of a book instead of reading every page.\nPrimary keys and UNIQUE columns get an index automatically.","r":"Index = fast lookup, like a book's index.","g":["index","z_database","primary_key","table","unique_constraint"],"fa":"A lookup structure, like a book's index, that lets the database find rows without reading the whole table","cat":"db"},{"id":"DB-35","t":"m","l":1,"q":"What does `SELECT DISTINCT country FROM users;` return?","o":["Every row's country, duplicates included","Each country only once","The number of countries","The first country"],"a":1,"e":"DISTINCT removes duplicate rows from the result. If 100 users are from Peru, 'Peru' appears once.\nTo count the different values: `SELECT COUNT(DISTINCT country) FROM users;`.","r":"DISTINCT = unique values only.","g":["sql","n_distinct","z_query","table","z_database","null"],"cat":"db"},{"id":"DB-36","t":"m","l":1,"q":"One customer can have many orders. Where does the link column go?","o":["An `order_id` column in the customers table","A `customer_id` column in orders, the 'many' side","A separate database that links both tables","Both tables store all ids as a list"],"a":1,"e":"In a one-to-many relationship, the 'many' side (orders) stores a foreign key pointing to the 'one' side (customers).\nEach order row has exactly one `customer_id`, while a customer row would need an unlimited list of order IDs, which tables do not store well.\nMany-to-many (students ↔ courses) needs a third 'join table' with both IDs.","r":"One-to-many: put the foreign key on the 'many' side.","g":["foreign_key","normalization","primary_key","schema","table","join"],"fa":"A `customer_id` column in orders (the 'many' side)","cat":"db"},{"id":"DB-37","t":"m","l":1,"q":"In a relational database, what are a table, a row and a column?","o":["A table is a file; a row is a folder; a column is a disk","Table: a kind of data. Row: a record. Column: an attribute","A row is a database; a column is a user of the database","They are all the same thing, with three different names"],"a":1,"e":"A relational database organizes data in tables, like spreadsheets with strict rules.\n- Table: a collection about one thing (`customers`).\n- Row (record): one item (customer 17).\n- Column (field): one property of every item with a data type (`email VARCHAR`, `age INT`).\nTables are linked with keys: a primary key identifies each row, and a foreign key in another table points to it.","r":"Table = entity, row = record, column = attribute.","g":["table","primary_key","d_relational","z_database","foreign_key","z_data_type"],"fa":"A table holds one kind of data; each row is one record (e.g. one customer); each column is one attribute (e.g. email) with a fixed type","cat":"db"},{"id":"DB-38","t":"m","l":1,"q":"What are the main groups of SQL commands?","o":["DDL, DML, DQL, DCL, TCL: structure, data, queries, rights, transactions","Only SELECT and INSERT, because all the others are variations","HTML, CSS and JS commands, which are used in web pages","Frontend and backend commands, used by different developers"],"a":0,"e":"SQL commands are grouped by purpose:\n- DDL (Data Definition Language): create or change the structure: `CREATE TABLE`, `ALTER TABLE`, `DROP TABLE`.\n- DML (Data Manipulation): change data: `INSERT`, `UPDATE`, `DELETE`.\n- DQL (Data Query): read data: `SELECT`.\n- DCL (Data Control): permissions: `GRANT`, `REVOKE`.\n- TCL (Transaction Control): `BEGIN`, `COMMIT`, `ROLLBACK`.","r":"DDL structure, DML change data, DQL read, DCL permissions, TCL transactions.","g":["sql","d_ddl_dml","transaction","n_sql_clauses","rollback"],"fa":"DDL (define structure: CREATE, ALTER, DROP), DML (change data: INSERT, UPDATE, DELETE), DQL (query: SELECT), DCL (permissions: GRANT, REVOKE), TCL (transactions: COMMIT, ROLLBACK)","cat":"db"},{"id":"DB-39","t":"m","l":2,"q":"What do 1NF, 2NF and 3NF mean in plain language?","o":["1NF: atomic values. 2NF: whole key. 3NF: only the key","They are three different types of index that speed up queries","They are three isolation levels that control the transactions","They are three types of backup that protect the database"],"a":0,"e":"Normalization organizes tables to avoid duplicated data and update bugs.\n- 1NF: one value per cell (no lists like \"red,blue\" in a column) and no repeated column groups.\n- 2NF: (with a composite key) every other column must depend on the entire key, not just part of it.\n- 3NF: columns must depend on the key and nothing else. Example: `orders(order_id, customer_id, customer_city)`: city depends on the customer, not the order, so move it to `customers`.\nMemory trick: \"the key, the whole key, and nothing but the key\".","r":"Data depends on the key, the whole key, and nothing but the key.","g":["normalization","d_normal_forms","d_junction","foreign_key","schema","table"],"fa":"1NF: each cell has one atomic value and no repeating groups. 2NF: every non-key column depends on the whole primary key. 3NF: non-key columns depend only on the key, not on other non-key columns","cat":"db"},{"id":"DB-40","t":"m","l":1,"q":"How do you model a many-to-many relationship, e.g. students and courses?","o":["Store a list of course ids in a single column of the students table","Create a junction table with two foreign keys, like `enrollments`","Duplicate the students table once for each course that exists","It cannot be modeled in a relational database at all"],"a":1,"e":"A student takes many courses and a course has many students. A relational column cannot hold a list, so you create a third table in the middle.\n`enrollments(student_id, course_id, enrolled_at)`: each row links one student with one course. The pair `(student_id, course_id)` is usually its primary key, preventing duplicates.\nThe junction table can also hold data about the relationship (date, grade).","ec":"CREATE TABLE enrollments (\n    student_id INT REFERENCES students(id),\n    course_id  INT REFERENCES courses(id),\n    enrolled_at DATE,\n    PRIMARY KEY (student_id, course_id)\n);","r":"Many-to-many = junction table with two foreign keys.","g":["d_junction","foreign_key","primary_key","table"],"fa":"Create a junction (join) table `enrollments(student_id, course_id)` with two foreign keys","cat":"db"},{"id":"DB-41","t":"m","l":2,"q":"What is the difference between `DELETE`, `TRUNCATE` and `DROP`?","o":["They are identical commands and only their names are different","DELETE removes chosen rows; TRUNCATE all rows; DROP the table","DROP removes only a single row from the table that is named","TRUNCATE deletes the whole database, not only one table"],"a":1,"e":"- `DELETE FROM t WHERE ...`: removes the rows you choose. Can be rolled back in a transaction, fires triggers, slower on big tables.\n- `TRUNCATE TABLE t`: empties the table very fast (no WHERE), resets auto-increment counters; in many databases it is DDL and harder to roll back.\n- `DROP TABLE t`: deletes the table itself, with structure, indexes and data.\nAlways test destructive statements inside a transaction or on a copy first.","r":"DELETE some rows, TRUNCATE all rows, DROP the table.","g":["d_ddl_dml","sql","n_sql_clauses","transaction"],"fa":"`DELETE` removes selected rows (can use WHERE, logged per row); `TRUNCATE` quickly removes all rows but keeps the table; `DROP` removes the entire table and its structure","cat":"db"},{"id":"DB-42","t":"m","l":2,"q":"In what logical order does SQL evaluate a query?","o":["SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY","FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT","ORDER BY, SELECT, FROM, WHERE, GROUP BY, HAVING","WHERE, SELECT, FROM, HAVING, GROUP BY, ORDER BY"],"a":1,"e":"You write `SELECT` first, but the database processes it later:\n1. `FROM` / `JOIN`: choose and combine tables.\n2. `WHERE`: filter rows.\n3. `GROUP BY`: form groups.\n4. `HAVING`: filter groups.\n5. `SELECT`: compute columns and aliases.\n6. `ORDER BY`: sort.\n7. `LIMIT`: cut.\nThis explains why you cannot use a `SELECT` alias inside `WHERE`, but you can in `ORDER BY`.","r":"FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.","g":["sql","group_by","n_sql_clauses","join"],"fa":"FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT","cat":"db"},{"id":"DB-43","t":"m","l":2,"q":"What is a view, and how does a materialized view differ?","o":["A view saves a query run on read; a materialized view saves a result","A view is a copy of the database; a materialized view is its backup","A view is always faster than a materialized view of the same query","There is no difference between a view and a materialized view"],"a":0,"e":"A view is a saved SELECT with a name: `SELECT * FROM active_customers`. It stores no data; each read re-runs the query. It simplifies queries and can hide columns for security.\nA materialized view stores the result on disk (like a cached table). Reads are fast, but data can be stale until you refresh it (`REFRESH MATERIALIZED VIEW`).\nUse materialized views for heavy reports.","r":"View = saved query. Materialized view = saved result.","g":["d_view","sql","z_query","table","index","cache"],"fa":"A view stores a saved query that runs each time you read it; a materialized view stores the query result physically and must be refreshed","cat":"db"},{"id":"DB-44","t":"m","l":2,"q":"Which query lists customers who have NO orders?","o":["`SELECT * FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)`","`SELECT * FROM customers c WHERE c.orders = 0 OR c.orders IS NULL OR c.order_count < 1`","`SELECT * FROM customers c INNER JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL`","`SELECT c.* FROM customers c WHERE c.id NOT IN (SELECT o.id FROM orders o) AND c.active`"],"a":0,"e":"`NOT EXISTS` with a correlated subquery checks, for each customer, whether any order row points to them. If none, the customer is returned.\nEquivalent: `LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL` (anti-join).\nBe careful with `NOT IN (subquery)`: if the subquery returns any NULL, the result becomes empty. `NOT EXISTS` avoids this problem.","ec":"SELECT c.*\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.id\nWHERE o.id IS NULL;","r":"Customers without orders: LEFT JOIN ... IS NULL, or NOT EXISTS.","g":["left_join","d_exists","n_sql_clauses","null","n_null_compare","join"],"cat":"db"},{"id":"DB-45","t":"m","l":2,"q":"What is a CTE (`WITH` clause) useful for?","o":["Creating physical tables on the disk of the database server","Naming a subquery so a complex query reads step by step","Encrypting the data that is returned by the query","Speeding up every query of the database automatically"],"a":1,"e":"A Common Table Expression gives a temporary name to a query inside a statement. It makes long queries readable: define step 1 and step 2 as named blocks, then combine them.\nExample: first compute totals per customer, then select the biggest ones.\n`WITH RECURSIVE` can walk hierarchies such as an employee-manager tree.","ec":"WITH totals AS (\n    SELECT customer_id, SUM(amount) AS total\n    FROM orders\n    GROUP BY customer_id\n)\nSELECT c.name, t.total\nFROM totals t\nJOIN customers c ON c.id = t.customer_id\nWHERE t.total > 1000;","r":"CTE = named subquery for readable queries.","g":["d_cte","sql","recursion","n_sql_clauses","group_by","join"],"fa":"Naming a subquery so a complex query becomes readable step by step (and allows recursion)","cat":"db"},{"id":"DB-46","t":"m","l":2,"q":"Which query finds duplicate emails in a `users` table?","o":["`SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1`","`SELECT DISTINCT email, COUNT(*) FROM users ORDER BY email DESC`","`SELECT email FROM users WHERE COUNT(email) > 1 GROUP BY email`","`SELECT email FROM users GROUP BY id HAVING COUNT(email) > 1`"],"a":0,"e":"Group rows by email, count how many rows are in each group, and keep only groups with more than one row. `HAVING` is used because the filter applies to the aggregated result (`WHERE` cannot use `COUNT`).\nTo prevent duplicates in the future, add a `UNIQUE` constraint on `email`.","r":"Duplicates: GROUP BY col HAVING COUNT(*) > 1.","g":["group_by","aggregate","n_count","n_sql_clauses","unique_constraint"],"cat":"db"},{"id":"DB-47","t":"m","l":3,"q":"What is a covering index?","o":["An index that holds every column a query needs, so no table read","An index that is created over all the tables of the database","An index that also works as a backup of the indexed table","An index that is protected with a password for each user"],"a":0,"e":"Normally an index finds the row location, then the database goes to the table to read the other columns (an extra step). If the index itself contains all columns the query selects and filters on, the table is never touched (an \"index-only scan\"), which is much faster.\nExample: query `SELECT email FROM users WHERE country = 'ES'` is covered by an index on `(country, email)`.\nThe cost: bigger indexes and slower writes.","r":"Covering index = the index alone answers the query.","g":["index","d_covering_index","z_query","time_complexity","table","n_sql_clauses"],"fa":"An index that includes every column a query needs, so the database can answer from the index without reading the table","cat":"db"},{"id":"DB-48","t":"m","l":2,"q":"What is the difference between a surrogate key and a natural key?","o":["A surrogate key is artificial (auto id, UUID); a natural key is real data","They are the same kind of key, but with two different names","Surrogate keys can never be unique, and natural keys always are","Natural keys are always numbers, and surrogate keys are text"],"a":0,"e":"Natural keys come from the data itself, but they can change (people change email) or be reused, and they can be long.\nSurrogate keys (`id BIGINT GENERATED ... AS IDENTITY`, UUID) are generated by the database, are small, stable and never change, which makes foreign keys simple.\nCommon practice: surrogate primary key, plus a UNIQUE constraint on the natural key.","r":"Surrogate = artificial stable id. Natural = real-world identifier.","g":["primary_key","d_surrogate_key","n_uuid","unique_constraint","foreign_key"],"fa":"A surrogate key is an artificial identifier with no business meaning (auto-increment id, UUID); a natural key is real-world data that identifies a row (email, passport number)","cat":"db"},{"id":"DB-49","t":"f","l":2,"q":"Design a relational schema for a library (books, authors, members, loans). Explain the relationships.","a":"- `authors(id, name)`, `books(id, title, isbn UNIQUE)`, `members(id, name, email UNIQUE)`.\n- Book to author is many-to-many (a book can have several authors): junction `book_authors(book_id, author_id)`.\n- A book can have several physical copies: `copies(id, book_id FK, status)`.\n- `loans(id, copy_id FK, member_id FK, loaned_at, due_at, returned_at NULL)`: one-to-many from member to loans and from copy to loans.\n- Constraints: primary keys, foreign keys, NOT NULL, UNIQUE (isbn, email), CHECK (due_at > loaned_at).\n- Indexes on foreign keys and on search columns (title). Normalize to 3NF; denormalize only with a measured reason.\n- Query example: members with overdue loans: `WHERE returned_at IS NULL AND due_at < now()`.","g":["foreign_key","unique_constraint","null","primary_key","n_null_compare","n_sql_clauses"],"cat":"db"},{"id":"DB-50","t":"f","l":1,"q":"Explain primary key, foreign key, index, constraint and transaction as if I know nothing.","a":"- Primary key: column(s) that uniquely identify each row (no duplicates, no null).\n- Foreign key: a column that points to the primary key of another table, creating a relationship and preventing orphan rows.\n- Index: an extra sorted structure that makes searches faster, at the cost of slower writes and more space.\n- Constraint: a rule the database enforces (NOT NULL, UNIQUE, CHECK, FOREIGN KEY).\n- Transaction: a group of operations that either all succeed or all fail (ACID), e.g. a money transfer.\n- Together they keep data correct (integrity) and queries fast.","g":["primary_key","foreign_key","transaction","unique_constraint","acid","null"],"cat":"db"},{"id":"DB-51","t":"m","l":0,"q":"What is a database?","o":["An organized collection of data that programs can store and search","A spreadsheet file that only one person can open at a time","A type of web browser that is used to connect to servers","A folder in which the backups of a company are stored"],"a":0,"e":"Applications need to remember things: users, orders, messages. A database keeps that data organized on disk so it survives when the program stops.\nCompared to plain files, a database lets many users read and write at the same time, searches quickly (indexes), and protects the data with rules and transactions.\nExamples: PostgreSQL, MySQL, Oracle Database, MongoDB.","r":"Database = organized, durable, shareable data.","g":["z_database","z_dbms","sql","nosql","table","z_crud"],"fa":"An organized collection of data that programs can store, search, update and share safely","cat":"db"},{"id":"DB-52","t":"m","l":0,"q":"What are PostgreSQL, MySQL and Oracle Database?","o":["Programming languages that are used for writing backend code","Database management systems: software that stores and queries data","Web servers that are used for serving the pages of a site","Operating systems that are used on the servers of a company"],"a":1,"e":"A DBMS is the program that manages a database: it stores the data, runs your queries and enforces the rules.\nThose three are relational DBMS: they store data in tables and you talk to them with SQL.\nWhen people say 'the database', they usually mean the data plus the DBMS that runs it.","r":"PostgreSQL, MySQL, Oracle = database software.","g":["z_dbms","sql","z_database","table"],"fa":"Database management systems (DBMS): software that stores data and answers queries","cat":"db"},{"id":"DB-53","t":"m","l":0,"q":"What is SQL?","o":["Structured Query Language, to read and change data in relational DBs","Simple Quick Language, which is used to design web pages","Server Query Link, which is a kind of cable for networks","Software Quality Layer, which is a tool for testing programs"],"a":0,"e":"SQL (Structured Query Language) is the standard way to talk to a relational database.\nExample: `SELECT name FROM users WHERE age > 30;` asks for the names of users older than 30.\nThe main commands: SELECT (read), INSERT (add), UPDATE (change), DELETE (remove).","r":"SQL = the language of relational databases.","g":["sql","z_query","d_relational","n_sql_clauses","z_database"],"fa":"Structured Query Language: the language used to read and change data in relational databases","cat":"db"},{"id":"DB-54","t":"m","l":0,"q":"CRUD means Create, Read, Update, Delete. Which SQL commands match these four in that order?","o":["INSERT, SELECT, UPDATE, DELETE","SELECT, INSERT, DELETE, UPDATE","ADD, GET, SET, REMOVE","MAKE, SHOW, CHANGE, DROP"],"a":0,"e":"Almost every application is built on four basic data operations:\n- Create: `INSERT INTO users ...`\n- Read: `SELECT ... FROM users`\n- Update: `UPDATE users SET ...`\n- Delete: `DELETE FROM users WHERE ...`\nIn a REST API they usually map to POST, GET, PUT or PATCH, and DELETE.","r":"CRUD = INSERT, SELECT, UPDATE, DELETE.","g":["z_crud","sql","n_sql_clauses","http_method","rest","api"],"cat":"db"},{"id":"DB-55","t":"m","l":0,"q":"In database language, what is a 'query'?","o":["A bug that appears inside the database when it is overloaded","A request to the database to get or change data, like `SELECT`","A backup file that is created by the database every night","A type of table that is used to store temporary rows"],"a":1,"e":"To query means to ask the database a question or give it an instruction.\nA read query uses SELECT and returns rows. A write query uses INSERT, UPDATE or DELETE and changes data.\nSlow queries are a common cause of slow applications, which is why indexes and EXPLAIN matter later.","r":"Query = a request to the database.","g":["z_query","sql","n_sql_clauses","z_database","explain"],"fa":"A request written to the database to get or change data, such as `SELECT name FROM users`","cat":"db"},{"id":"DB-56","t":"m","l":0,"q":"Why do applications store important data in a database instead of only in program variables?","o":["Variables are slower to write to than a database is","Variables live in RAM and vanish at exit; a DB persists","Databases are required by law for any kind of application","Variables cannot store text values, only plain numbers"],"a":1,"e":"Memory (RAM) is fast but temporary. If the app restarts or the computer shuts down, everything in variables is gone.\nA database writes data to disk, so it persists. That is called persistence.\nMany apps combine both: memory or a cache (like Redis) for speed, a database for safety.","r":"Memory is temporary. Databases persist data.","g":["z_persistence","cache","n_ram","z_database","z_variable","redis"],"fa":"Variables live in memory (RAM) and disappear when the program stops or restarts; a database saves data on disk so it survives","cat":"db"},{"id":"DB-57","t":"m","l":0,"q":"Which of these are relational (SQL) databases?","o":["PostgreSQL and MySQL","Redis and MongoDB","Git and Docker","HTML and CSS"],"a":0,"e":"Relational databases store data in tables with rows and columns and use SQL: PostgreSQL, MySQL, Oracle Database, Microsoft SQL Server.\nRedis (key-value store) and MongoDB (document store) are usually called NoSQL.\nGit and Docker are developer tools, and HTML/CSS are web languages, not databases.","r":"Tables + SQL = relational.","g":["sql","nosql","table","d_relational","redis","html"],"cat":"db"},{"id":"DB-58","t":"m","l":0,"q":"What does a database schema describe?","o":["The physical building in which the servers are placed","The structure of the data: tables, columns, types and relations","The password rules that the database enforces for users","The schedule on which the backups of the data are taken"],"a":1,"e":"The schema is the blueprint of a database.\nExample: a table `users` with columns `id` (number), `email` (text), `created_at` (date), and a table `orders` with a `user_id` that points to `users.id`.\nChanging the schema (adding a column, for example) is called a migration.","r":"Schema = the structure of the data.","g":["schema","table","primary_key","foreign_key","index","z_dbms"],"fa":"The structure of the data: which tables exist, their columns and types, and how they relate","cat":"db"},{"id":"DB-59","t":"f","l":0,"q":"Explain what a database is and why almost every app needs one.","a":"- A database is where an app keeps its data on disk in an organized way: users, orders, messages.\n- Without it, data would live only in memory and disappear when the program stops.\n- It lets many people read and write at the same time without breaking each other's work.\n- It finds data fast (indexes) and protects it with rules (constraints) and transactions.\n- You talk to a relational database using SQL; examples are PostgreSQL and MySQL.","g":["z_database","sql","z_persistence","d_relational","transaction"],"cat":"db"},{"id":"ALG-01","t":"m","l":1,"q":"Time complexity of binary search on a sorted array?","o":["O(1)","O(log n)","O(n)","O(n log n)"],"a":1,"e":"Binary search looks at the middle element. If the target is smaller, it throws away the right half; if bigger, the left half. Then it repeats on what is left.\nEach step halves the remaining items: 1,000,000 → 500,000 → 250,000 ... so it needs only about 20 steps. That is O(log n).\nIt only works on SORTED data. Python has it in the `bisect` module.","r":"Halving each step = O(log n).","g":["binary_search","big_o","time_complexity","array"],"cat":"algo"},{"id":"ALG-02","t":"m","l":1,"q":"Average and worst-case lookup in a hash table?","o":["O(1) on average, O(n) in the worst case","O(log n) in both the average and worst case","O(1) in both the average and worst case","O(n) on average, O(n²) in the worst case"],"a":0,"e":"A hash table (Python dict or set) computes a hash of the key to jump directly to the right slot, so a lookup takes about the same time no matter how big it is: O(1) on average.\nIf many keys land in the same slot (collisions), it must check them one by one; in the worst case that is O(n). Good hash functions make this very rare.","r":"dict/set lookup ≈ O(1).","g":["hash_table","big_o","collision","hashing","table"],"fa":"O(1) average, O(n) worst","cat":"algo"},{"id":"ALG-03","t":"m","l":2,"q":"What is the lower bound for comparison-based sorting?","o":["O(n)","O(n log n)","O(log n)","O(n²)"],"a":1,"e":"A comparison sort only learns about the data by comparing two items ('is a < b?'). It can be proven that, in the worst case, any such algorithm needs about n log n comparisons.\nSo merge sort, heapsort and Timsort (O(n log n)) are already optimal.\nSorts that do not compare, like counting sort or radix sort, can be O(n) for limited kinds of keys (e.g. small integers).","r":"Comparison sorting can't beat O(n log n).","g":["big_o","sorting","quicksort","heap","time_complexity","tree"],"cat":"algo"},{"id":"ALG-04","t":"m","l":2,"q":"Worst case of quicksort, and when does it happen?","o":["O(n log n) on average, and never worse on any input","O(n²) when pivots are bad, like a sorted input","O(n) when the input array is already sorted","O(log n) when the pivot is always the median"],"a":1,"e":"Quicksort picks a pivot, puts smaller items on its left and larger on its right, then sorts each side.\nIf the pivot is always the smallest or largest item (e.g. picking the first element of an already sorted list), one side is empty every time, so it does n + (n-1) + ... steps = O(n²).\nRandom pivots or median-of-three make that extremely unlikely. Python's `sorted` uses Timsort, which is O(n log n) in the worst case.","r":"Quicksort: O(n log n) average, O(n²) with bad pivots.","g":["quicksort","big_o","recursion","time_complexity","sorting","array","amortized"],"fa":"O(n²), with consistently bad pivots (e.g. first element on already sorted input)","cat":"algo"},{"id":"ALG-05","t":"m","l":2,"q":"Which is true about merge sort?","o":["It sorts in place with O(1) memory, but it is not stable","It is stable, O(n log n) always, and needs O(n) extra space","Its worst case is O(n²) when the input is nearly sorted","It only works on linked lists, never on plain arrays"],"a":1,"e":"Merge sort splits the list in halves until single items remain, then merges sorted halves back together. Every level takes O(n) work and there are log n levels: O(n log n), always.\nMerging needs a temporary array: O(n) extra memory.\nIt is stable: equal items keep their original order, which matters when you sort by one field after another.","r":"Merge sort = always O(n log n), stable, needs extra memory.","g":["merge_sort","sorting","big_o","array"],"fa":"Stable, O(n log n) in all cases, O(n) extra space for arrays","cat":"algo"},{"id":"ALG-06","t":"m","l":2,"q":"Two Sum: find indices of two numbers adding to `target`. Optimal approach?","o":["Two nested loops over the array, O(n²)","Sort first, then binary search for each value, O(n log n)","One pass with a hash map from value to index, O(n)","Recursion that tries every pair of numbers"],"a":2,"e":"For each number x, the partner we need is `target - x`. Instead of searching the whole list for it (O(n) each time), we keep a dict of numbers already seen and their index.\nCheck the dict (O(1)); if the partner is there, done; otherwise store x. One pass: O(n).\nThis trade of memory for speed with a hash map is one of the most common interview tricks.","ec":"def two_sum(nums, target):\n    seen = {}                      # value -> index\n    for i, x in enumerate(nums):\n        if target - x in seen:\n            return [seen[target - x], i]\n        seen[x] = i","r":"Need 'have I seen X before?' fast → hash map.","g":["hash_table","big_o","time_complexity","space_complexity","array","two_pointers"],"fa":"One pass with a hash map from value to index, O(n) time, O(n) space","cat":"algo"},{"id":"ALG-07","t":"m","l":2,"q":"Detect a cycle in a linked list with O(1) extra space?","o":["Store each visited node in a hash set and look for repeats","Floyd's: a slow and a fast pointer meet when there is a cycle","Reverse the list in place and compare it with the original","Sort the nodes by value and look for any repeated nodes"],"a":1,"e":"Use two pointers: the slow one moves 1 node per step, the fast one 2 nodes.\nIf the list ends, there is no cycle. If there IS a cycle, the fast pointer eventually laps the slow one inside the loop and they meet, like two runners on a circular track.\nA set of visited nodes also works but uses O(n) memory.","r":"Cycle detection: fast and slow pointers.","g":["linked_list","two_pointers","n_floyd","space_complexity","time_complexity"],"fa":"Floyd's tortoise and hare: slow moves 1, fast moves 2; they meet if there is a cycle","cat":"algo"},{"id":"ALG-08","t":"m","l":2,"q":"Shortest path (fewest edges) in an unweighted graph?","o":["DFS","BFS","Dijkstra with a max-heap","Topological sort"],"a":1,"e":"BFS (breadth-first search) explores in rings: first all neighbors 1 step away, then all at 2 steps, and so on, using a queue.\nSo the first time BFS reaches a node, it got there with the fewest possible edges.\nDFS goes deep along one path first, so the first path it finds may be long. Cost of BFS: O(V + E).","r":"Fewest steps in an unweighted graph → BFS.","g":["bfs","dfs","graph","queue"],"cat":"algo"},{"id":"ALG-09","t":"m","l":3,"q":"Dijkstra's algorithm requires…","o":["A directed acyclic graph (DAG)","Edge weights that are not negative","A graph without weights on its edges","An adjacency matrix as the representation"],"a":1,"e":"Dijkstra finds shortest paths when edges have weights (distances, costs). It always expands the closest unvisited node next (using a min-heap) and treats its distance as final.\nThat 'final' decision is only correct if no edge can make a path shorter later, i.e. no negative weights.\nWith negative weights use Bellman-Ford. Complexity with a heap: O((V + E) log V).","r":"Dijkstra = weighted shortest path, no negative edges.","g":["dijkstra","graph","heap"],"fa":"Non-negative edge weights","cat":"algo"},{"id":"ALG-10","t":"m","l":3,"q":"You need an order to install packages given 'A depends on B' relations. Algorithm?","o":["Binary search on the list of packages","Topological sort (Kahn's algorithm or DFS) on a DAG","Kruskal's algorithm for a minimum spanning tree","Quickselect on the number of dependencies"],"a":1,"e":"Dependencies form a directed graph. A topological sort lists the nodes so every node comes after everything it depends on.\nKahn's algorithm: repeatedly take a node with no remaining dependencies (in-degree 0), output it, and remove its edges.\nIf some nodes are never freed, there is a cycle (circular dependency), and no valid order exists.","r":"Order with dependencies → topological sort.","g":["topological_sort","dag","graph","dfs"],"cat":"algo"},{"id":"ALG-11","t":"m","l":2,"q":"Best way to get the k largest elements from a stream of n numbers?","o":["Sort all n numbers first: O(n log n)","Keep a min-heap of size k: O(n log k)","Push all n into a max-heap, then pop k","Scan the numbers k times: O(nk) overall"],"a":1,"e":"A heap is a structure that always gives you its smallest item in O(1) and adds/removes in O(log size).\nKeep a min-heap with the k largest numbers seen so far. For each new number, push it; if the heap has more than k items, pop the smallest.\nThe heap never grows past k, so the cost is O(n log k), and memory is only O(k). Python: `heapq.nlargest(k, numbers)`.","r":"Top k → heap of size k.","g":["heap","big_o","time_complexity","queue","sorting","space_complexity"],"cat":"algo"},{"id":"ALG-12","t":"m","l":2,"q":"Longest substring without repeating characters. Optimal technique and complexity?","o":["Brute force over all substrings, O(n³)","Sliding window with a last-seen map, O(n)","Sort the characters first, O(n log n)","A DP table over all substring pairs, O(n²)"],"a":1,"e":"A sliding window is a range [left, right] over the string that you grow and shrink instead of restarting.\nMove `right` forward one character at a time. If that character already appears inside the window, move `left` just past its previous position. Track the best window length.\nEach pointer only moves forward, so the total work is O(n).","r":"Best contiguous substring/subarray → sliding window.","g":["sliding_window","hash_table","two_pointers","time_complexity","space_complexity","array"],"cat":"algo"},{"id":"ALG-13","t":"m","l":2,"q":"In a sorted array, find whether two numbers sum to target using O(1) space.","o":["Hash set of the numbers seen so far (O(n) space)","Two pointers from both ends, moving by the sum","Build a binary search tree from the whole array","Recursively try every pair of numbers in the array"],"a":1,"e":"Put one pointer at the start (smallest) and one at the end (largest).\nIf their sum is too small, move the left pointer right to get a bigger number. If too big, move the right pointer left. If equal, done.\nBecause the array is sorted, each move safely discards one candidate: O(n) time, no extra memory.","r":"Sorted array + pair search → two pointers.","g":["two_pointers","binary_search","sorting","space_complexity","time_complexity"],"fa":"Two pointers from both ends, moving inward based on the sum","cat":"algo"},{"id":"ALG-14","t":"m","l":2,"q":"Which two properties indicate a problem fits dynamic programming?","o":["Sorted input and unique values","Overlapping subproblems and optimal substructure","Graph input and the presence of cycles","Recursion and some randomness in the choices"],"a":1,"e":"Dynamic programming (DP) solves a big problem by combining answers to smaller versions of it, and saves each small answer so it is computed only once.\nIt fits when:\n- Optimal substructure: the best answer is built from best answers of subproblems.\n- Overlapping subproblems: the same subproblems come up again and again.\nTwo styles: top-down with memoization (`@lru_cache`) or bottom-up filling a table.","r":"DP = solve subproblems once and reuse them.","g":["dp","memoization","recursion","time_complexity","space_complexity","base_case"],"cat":"algo"},{"id":"ALG-15","t":"m","l":2,"q":"Time complexity of memoized Fibonacci `fib(n)`?","o":["O(2ⁿ)","O(n)","O(log n)","O(n²)"],"a":1,"e":"Naive recursive fib calls fib(n-1) and fib(n-2), which call the same values again and again: about 2ⁿ calls.\nWith memoization, each fib(k) is computed once and then read from a cache. There are only n different values, so O(n).","ec":"from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef fib(n):\n    return n if n < 2 else fib(n - 1) + fib(n - 2)","r":"Memoization turns repeated work into one-time work.","g":["memoization","dp","big_o","time_complexity","n_lru_cache"],"cat":"algo"},{"id":"ALG-16","t":"m","l":2,"q":"A deep recursive DFS in Python on a 100,000-node path graph will likely…","o":["Run fine, since Python optimizes deep recursion","Hit a RecursionError, since the default limit is about 1000","Run in O(1) space, using the same stack frame","Be optimized by tail-call elimination in the interpreter"],"a":1,"e":"Every recursive call adds a frame to the call stack. Python limits the depth to about 1000 frames by default to avoid crashing.\nA path of 100,000 nodes needs 100,000 nested calls → RecursionError. Python does not optimize tail calls.\nFix: write it iteratively with your own stack (a list).","ec":"def dfs(start):\n    stack, seen = [start], {start}\n    while stack:\n        node = stack.pop()\n        for nxt in graph[node]:\n            if nxt not in seen:\n                seen.add(nxt)\n                stack.append(nxt)","r":"Deep recursion in Python → convert to a loop with a stack.","g":["recursion","call_stack","dfs","stack","graph"],"fa":"Hit RecursionError (default limit ~1000)","cat":"algo"},{"id":"ALG-17","t":"m","l":1,"q":"Validate a string of brackets like `\"([]{})\"`. Data structure?","o":["Queue","Stack","Heap","Trie"],"a":1,"e":"A stack is last-in, first-out, like a pile of plates.\nWalk through the string: push every opening bracket. On a closing bracket, the top of the stack must be its matching opener; pop it. If it doesn't match, or the stack is empty, the string is invalid.\nAt the end the stack must be empty. O(n).","r":"Matching pairs / nesting → stack.","g":["stack","queue","array","time_complexity","space_complexity","z_data_structure"],"cat":"algo"},{"id":"ALG-18","t":"m","l":2,"q":"Implementing a queue with two stacks gives what cost per operation?","o":["O(n) each","O(1) amortized","O(log n)","O(n²) total"],"a":1,"e":"Push new items onto stack `in`. To dequeue, pop from stack `out`; if `out` is empty, first move everything from `in` to `out`, which reverses the order so the oldest is on top.\nA single move can be expensive, but each item is moved at most once in its life. Spread over all operations, the average cost is O(1): that is 'amortized' O(1).","r":"Each item moves once → amortized O(1).","g":["queue","stack","amortized","n_fifo_lifo","time_complexity","space_complexity"],"cat":"algo"},{"id":"ALG-19","t":"m","l":2,"q":"Autocomplete over a dictionary of words by prefix. Best structure?","o":["A hash set of all the words","A trie (prefix tree)","A min-heap ordered by word length","A linked list of the words in order"],"a":1,"e":"A trie is a tree where each edge is a letter. Words with the same beginning share the same path: 'car', 'cart' and 'care' all go through c → a → r.\nTo autocomplete 'ca', walk 2 steps down and collect all words below that node.\nLookup time depends on the prefix length, not on how many words are stored.","r":"Prefix search → trie.","g":["trie","tree","hash_table","time_complexity","space_complexity","sorting"],"fa":"Trie (prefix tree)","cat":"algo"},{"id":"ALG-20","t":"m","l":3,"q":"Count connected components while edges arrive dynamically. Best structure?","o":["Union-Find with path compression and ranks","A stack that stores the vertices of each group","A binary search tree of all the vertices seen","A Bloom filter that stores the edges so far"],"a":0,"e":"Union-Find keeps groups of elements. `find(x)` returns the group leader; `union(a, b)` merges two groups.\nWhen an edge a-b arrives, union them; the number of components drops by one if they were in different groups.\nWith path compression and union by rank, each operation is almost O(1). Also used for Kruskal's minimum spanning tree.","r":"Dynamic 'are these connected?' → Union-Find.","g":["union_find","graph","dag","time_complexity","amortized","dfs"],"fa":"Union-Find (disjoint set) with path compression and union by rank","cat":"algo"},{"id":"ALG-21","t":"m","l":2,"q":"Which traversal of a binary search tree yields keys in sorted order?","o":["Pre-order","In-order","Post-order","Level-order"],"a":1,"e":"In a BST, every key in a node's left subtree is smaller and every key in its right subtree is bigger.\nIn-order traversal visits left subtree, then the node, then right subtree, so it naturally outputs keys from smallest to largest.\nPre-order (node first) is used to copy trees; post-order (node last) to delete them.","r":"BST + in-order = sorted output.","g":["bst","tree","dfs","binary_search"],"cat":"algo"},{"id":"ALG-22","t":"m","l":2,"q":"Worst-case search time in an unbalanced BST built from sorted input?","o":["O(1)","O(log n)","O(n)","O(n log n)"],"a":2,"e":"Inserting 1, 2, 3, 4, 5 in order into a plain BST makes each new key the right child of the previous one. The 'tree' is really a straight line, like a linked list.\nSearching then visits every node: O(n).\nSelf-balancing trees (AVL, red-black) reorganize themselves to keep height about log n, guaranteeing O(log n).","r":"Unbalanced BST can degrade to O(n).","g":["bst","tree","big_o","linked_list"],"cat":"algo"},{"id":"ALG-23","t":"m","l":1,"q":"What does this function return and what are its time/space costs?","c":"def f(nums):\n    seen = set()\n    for n in nums:\n        if n in seen:\n            return n\n        seen.add(n)\n    return -1","o":["Smallest value; O(n log n) time, O(1) space","First duplicate value; O(n) time, O(n) space","Count of duplicates; O(n²) time, O(1) space","Last unique value; O(n) time, O(1) space"],"a":1,"e":"It walks the list once and remembers each number in a set. The first number already in the set is the first repeated value, so it returns it.\nOne loop, with O(1) set checks inside: O(n) time. The set can grow to n items: O(n) extra memory.\nWithout the set you would compare every pair: O(n²).","r":"A set turns 'have I seen it?' into O(1).","g":["hash_table","big_o","space_complexity","z_loop"],"cat":"algo"},{"id":"ALG-24","t":"m","l":3,"q":"Space complexity of recursive DFS on a binary tree of height h?","o":["O(1), since no extra memory is allocated","O(h) for the recursion call stack","O(n²), since each node is visited twice","O(log h) for the depth of the call stack"],"a":1,"e":"Recursive DFS keeps one call-stack frame for each node on the current path from the root. The longest path has h nodes, so memory is O(h).\nFor a balanced tree h ≈ log n; for a completely skewed tree h = n.\nBFS instead keeps a whole level in its queue: O(width).","r":"Recursion memory = depth of the recursion.","g":["dfs","call_stack","space_complexity","recursion","stack","bfs"],"fa":"O(h) for the call stack","cat":"algo"},{"id":"ALG-25","t":"m","l":1,"q":"In a Python list, `append(x)` and `insert(0, x)` cost…","o":["Both are O(1) in the average case","append: O(1) amortized; insert(0): O(n)","Both are O(n) since the list is copied","append: O(n); insert(0): O(1) in CPython"],"a":1,"e":"A Python list is a dynamic array: items sit next to each other in memory.\nAdding at the END just uses the next free slot: O(1) (occasionally the array grows, but on average still O(1)).\nInserting at the FRONT means shifting every existing item one place to the right: O(n). Use `collections.deque` if you need fast front inserts.","r":"List end = fast. List front = slow.","g":["array","amortized","big_o","deque","n_dynamic_array"],"fa":"append O(1) amortized, insert(0, x) O(n)","cat":"algo"},{"id":"ALG-26","t":"m","l":1,"q":"Repeated `x in data` checks inside a loop are slow. `data` is a list of 1M items. Fix?","o":["Sort the list once so the checks run faster","Build a `set` once, so each check is O(1)","Convert it to a tuple, which searches faster","Call `data.index(x)` for each of the checks"],"a":1,"e":"`x in some_list` checks items one by one: O(n). Doing it inside a loop of n iterations costs O(n²), which is huge for a million items.\n`x in some_set` uses hashing: O(1) on average.\nConverting once costs O(n), then all checks are cheap.","r":"Many membership checks → use a set.","g":["hash_table","big_o","linear_search","set","time_complexity","space_complexity"],"fa":"Convert to a `set` once, making each check O(1) average","cat":"algo"},{"id":"ALG-27","t":"m","l":3,"q":"Maximum subarray sum in O(n)?","o":["Kadane's algorithm","Floyd-Warshall","Binary search","Merge sort"],"a":0,"e":"Kadane's idea: walk through the array keeping `cur`, the best sum of a subarray that ends at the current position.\nAt each number x, either extend the previous subarray (`cur + x`) or start fresh at x, whichever is bigger. Track the best `cur` ever seen.\nOne pass, O(n) time, O(1) memory.","ec":"def max_subarray(nums):\n    best = cur = nums[0]\n    for x in nums[1:]:\n        cur = max(x, cur + x)\n        best = max(best, cur)\n    return best","r":"Kadane: extend or restart at each element.","g":["kadane","dp","time_complexity","space_complexity","sliding_window"],"cat":"algo"},{"id":"ALG-28","t":"m","l":3,"q":"Generating all permutations of n distinct elements takes at least…","o":["O(n), because each element is visited once","O(n²), because each pair is compared","O(n!) outputs, and O(n · n!) to write them","O(2ⁿ), because each element is in or out"],"a":2,"e":"There are n! orderings (3 items: 6; 10 items: 3,628,800), and each permutation has n elements to write out.\nSuch problems are solved with backtracking: choose an element, recurse on the rest, then undo the choice and try the next.\nFor comparison, the number of subsets is 2ⁿ.","r":"Permutations = n!, subsets = 2ⁿ.","g":["backtracking","recursion","big_o","time_complexity","space_complexity","n_permutations"],"fa":"O(n!) outputs, O(n · n!) to write them","cat":"algo"},{"id":"ALG-29","t":"m","l":2,"q":"For a sparse graph (E much smaller than V²), which representation is preferred?","o":["Adjacency matrix","Adjacency list","Edge-weight matrix","Incidence matrix"],"a":1,"e":"An adjacency list stores, for each node, only the list of its actual neighbors: O(V + E) memory. In Python: `{\"A\": [\"B\", \"C\"], ...}`.\nAn adjacency matrix is a V × V grid of yes/no, which wastes memory when most pairs are not connected, but checks 'is A connected to B?' in O(1).\nMost real graphs (social networks, roads) are sparse.","r":"Sparse graph → adjacency list.","g":["adjacency_list","graph","space_complexity","time_complexity","bfs","dfs","dag"],"cat":"algo"},{"id":"ALG-30","t":"m","l":2,"q":"Answer many `sum(nums[i:j])` range queries on a static array quickly?","o":["Recompute each sum on demand, O(n) per query","Prefix sums: each query is `p[j] - p[i]`","Sort the array once, then slice the range","Keep a stack of partial sums for each query"],"a":1,"e":"Build `prefix` where `prefix[k]` is the sum of the first k elements. This takes one pass.\nThen the sum of any range i..j-1 is `prefix[j] - prefix[i]`: one subtraction.\nFor example nums = [3, 1, 4]: prefix = [0, 3, 4, 8]; sum of nums[1:3] = 8 - 3 = 5.","r":"Many range sums → prefix sums.","g":["prefix_sum","time_complexity","space_complexity","array"],"fa":"Precompute prefix sums once (O(n)); each query is `prefix[j] - prefix[i]` (O(1))","cat":"algo"},{"id":"ALG-31","t":"m","l":3,"q":"'Next greater element' for each array item in O(n) uses…","o":["A monotonic stack","A min-heap","Binary search on a sorted copy","A trie of the values"],"a":0,"e":"Keep a stack of indexes whose next greater element is not known yet; their values are in decreasing order (that is why it is called 'monotonic').\nWhen a new value is bigger than the top of the stack, it IS the answer for that item: pop it and record the answer. Repeat, then push the new index.\nEach index is pushed and popped once: O(n).","r":"'Next greater/smaller' → monotonic stack.","g":["monotonic_stack","stack","time_complexity","space_complexity","array"],"cat":"algo"},{"id":"ALG-32","t":"m","l":3,"q":"An LRU cache with O(1) get and put is typically built with…","o":["A sorted list ordered by last use","A hash map plus a doubly linked list","A min-heap ordered by timestamp","Two stacks that swap their items"],"a":1,"e":"LRU = Least Recently Used: when full, remove the item that was used longest ago.\nThe hash map finds any item in O(1). The doubly linked list keeps items in usage order: move an item to the front when used, remove from the back when full, both O(1).\nIn Python, `OrderedDict` (with `move_to_end` and `popitem(last=False)`) does exactly this.","r":"LRU cache = hash map + doubly linked list.","g":["lru","hash_table","linked_list","cache"],"cat":"algo"},{"id":"ALG-33","t":"m","l":3,"q":"For a positive integer n, what does `n & (n - 1) == 0` test?","o":["n is an even number","n is a power of two","n is a prime number","n is an odd number"],"a":1,"e":"In binary, a power of two has exactly one 1 bit: 8 = 1000. Subtracting 1 flips that bit and turns all lower bits into 1: 7 = 0111.\nThe AND (&) of 1000 and 0111 is 0000. Any number with two or more 1 bits keeps at least one, so the result is not 0.\nThe same trick `n & (n - 1)` removes the lowest 1 bit, which helps count bits.","r":"n & (n-1) == 0 → power of two.","g":["bit_manipulation","n_bitwise","space_complexity","big_o"],"cat":"algo"},{"id":"ALG-34","t":"m","l":3,"q":"A dynamic array doubles capacity when full. Amortized cost of append?","o":["O(n)","O(log n)","O(1)","O(n²)"],"a":2,"e":"Most appends just use a free slot: O(1). When the array is full, it allocates double the space and copies everything: O(n) for that one append.\nBut copies happen only at sizes 1, 2, 4, 8, ... and they add up to less than 2n over n appends. Averaged over all appends, each costs O(1).\nThat average-over-many reasoning is called amortized analysis.","r":"Rare expensive steps averaged over many cheap ones = amortized.","g":["amortized","array","n_dynamic_array","time_complexity","space_complexity","big_o"],"cat":"algo"},{"id":"ALG-35","t":"f","l":1,"q":"How do you approach a coding problem you have never seen in an interview?","a":"- Restate the problem; ask about input size, constraints and edge cases (empty input, duplicates, negatives).\n- Work through 1-2 small examples by hand.\n- Describe a brute-force solution and its complexity first.\n- Look for patterns: hash map, two pointers, sliding window, sorting, heap, BFS/DFS, DP, binary search.\n- Agree on the approach, then code cleanly with clear names, thinking aloud.\n- Test with your examples and edge cases; trace the code line by line.\n- State the final time and space complexity and possible improvements.","g":["big_o","edge_case","space_complexity","sliding_window","binary_search","two_pointers","bfs","dfs"],"cat":"algo"},{"id":"ALG-36","t":"f","l":2,"q":"How does a hash map work internally?","a":"- An array of buckets. `hash(key) % capacity` chooses the bucket.\n- Collisions (two keys, same bucket): chaining (a small list per bucket) or open addressing (try the next slots; Python dicts do this).\n- When it gets too full (load factor), it resizes: a bigger array and every key re-placed. Amortized O(1) inserts.\n- Keys must be hashable and must not change; equal keys must have equal hashes.\n- Average O(1) get/put/delete; worst case O(n) with many collisions.","g":["hash_table","collision","amortized","array"],"cat":"algo"},{"id":"ALG-37","t":"f","l":2,"q":"Reverse a singly linked list iteratively. Explain the pointers.","a":"- Keep `prev = None` and `curr = head`.\n- Loop: save `nxt = curr.next`, point `curr.next = prev`, then move `prev = curr`, `curr = nxt`.\n- When `curr` is None, `prev` is the new head.\n- O(n) time, O(1) memory. A recursive version uses O(n) stack.","ac":"def reverse(head):\n    prev, curr = None, head\n    while curr:\n        nxt = curr.next\n        curr.next = prev\n        prev, curr = curr, nxt\n    return prev","g":["linked_list","time_complexity","space_complexity","two_pointers","recursion","base_case"],"cat":"algo"},{"id":"ALG-38","t":"m","l":1,"q":"What does Big-O notation describe?","o":["The exact running time of a program in seconds","How time or memory grows as the input size grows","The size of the source code, measured in lines","The number of bugs a program has in total"],"a":1,"e":"Big-O ignores machine speed and small details and answers: if the input becomes 10 times bigger, how much more work is needed?\n- O(1): constant, same work for any size.\n- O(log n): grows very slowly.\n- O(n): grows in proportion.\n- O(n²): 10× input → 100× work.\nIt usually describes the worst case.","r":"Big-O = how cost grows with input size.","g":["big_o","time_complexity","space_complexity","amortized","z_algorithm","sorting"],"fa":"How the running time (or memory) grows as the input size grows","cat":"algo"},{"id":"ALG-39","t":"m","l":1,"q":"What is the time complexity?","c":"def total(nums):\n    s = 0\n    for x in nums:\n        s += x\n    return s","o":["O(1)","O(n)","O(n²)","O(log n)"],"a":1,"e":"The loop runs once for each of the n items, and each iteration does a constant amount of work (one addition).\nn iterations × constant work = O(n), called linear time: double the list, double the time.","r":"One loop over n items = O(n).","g":["big_o","time_complexity"],"cat":"algo"},{"id":"ALG-40","t":"m","l":1,"q":"What is the time complexity?","c":"def has_pair(nums):\n    for a in nums:\n        for b in nums:\n            if a != b and a + b == 0:\n                return True\n    return False","o":["O(n)","O(n log n)","O(n²)","O(2n)"],"a":2,"e":"For each of the n items in the outer loop, the inner loop runs n times: n × n = n² iterations.\nO(n²) is called quadratic: with 1,000 items that is about 1,000,000 checks; with 100,000 items, 10 billion.\nA set can solve this specific problem in O(n).","r":"Loop inside a loop over the same data = O(n²).","g":["big_o","time_complexity"],"cat":"algo"},{"id":"ALG-41","t":"m","l":1,"q":"Accessing the 1000th element: array (Python list) vs linked list?","o":["Both are O(1), since the position is known","Array: O(1); linked list: O(n), node by node","Array: O(n); linked list: O(1) with an index","Both are O(log n), halving the search space"],"a":1,"e":"An array stores items next to each other in memory, so the position of item k can be calculated directly: O(1).\nA linked list stores items in separate nodes, each pointing to the next. To reach item 1000 you must follow 1000 links: O(n).\nIn exchange, a linked list can insert or remove a node in O(1) once you are at the right place.","r":"Array = fast access by index. Linked list = fast insert where you are.","g":["array","linked_list","time_complexity","space_complexity","amortized","big_o"],"fa":"Array O(1); linked list O(n) because you must walk node by node","cat":"algo"},{"id":"ALG-42","t":"m","l":1,"q":"A stack is…","o":["First in, first out (FIFO): the oldest leaves first","Last in, first out (LIFO): the newest leaves first","Kept sorted automatically as items are added","A kind of database used to hold temporary data"],"a":1,"e":"Think of a pile of plates: you put a plate on top (push) and take the top one (pop). The last plate added is the first removed.\nIn Python a list works as a stack: `append()` to push, `pop()` to pop, both O(1).\nUses: undo history, matching brackets, the function call stack, DFS.","r":"Stack = LIFO (pile of plates).","g":["stack","n_fifo_lifo","call_stack","dfs"],"fa":"Last in, first out (LIFO): you take from the top what you put last","cat":"algo"},{"id":"ALG-43","t":"m","l":1,"q":"A queue is…","o":["Last in, first out (LIFO): the newest leaves first","First in, first out (FIFO): the oldest leaves first","Random order, with no rule for what is removed","A structure that stores only numbers, not text"],"a":1,"e":"Like a line at the supermarket: people join at the back and are served from the front.\nIn Python use `collections.deque`: `append()` adds at the back, `popleft()` removes from the front, both O(1).\nUses: task queues, BFS, buffering messages.","r":"Queue = FIFO (supermarket line).","g":["queue","deque","n_fifo_lifo","bfs"],"fa":"First in, first out (FIFO): the first item added is the first removed","cat":"algo"},{"id":"ALG-44","t":"m","l":1,"q":"Why must every recursive function have a base case?","c":"def countdown(n):\n    if n == 0:          # base case\n        return\n    print(n)\n    countdown(n - 1)    # recursive case","o":["It makes the function run faster on large inputs","Without it, the calls never stop (RecursionError)","Python requires it as part of the function syntax","It lets the function return a value to its caller"],"a":1,"e":"Recursion means a function calls itself on a smaller version of the problem.\nThe base case is the simplest input that is answered directly, without another call (here n == 0). Each call must move closer to it.\nWithout a base case, the calls never stop and Python raises RecursionError when the call stack is too deep.","r":"Recursion = base case + smaller recursive call.","g":["recursion","base_case","call_stack","stack"],"fa":"Without a condition that stops the recursion, the function calls itself forever (RecursionError)","cat":"algo"},{"id":"ALG-45","t":"m","l":1,"q":"Searching an unsorted list by checking each item one by one is…","o":["O(1), since each item is checked once","O(log n), by halving the list","O(n): linear search","O(n²), by comparing every pair"],"a":2,"e":"Linear search starts at the first item and compares each one until it finds the target or reaches the end. In the worst case it looks at all n items: O(n).\nIf the list were sorted you could use binary search (O(log n)); if you need many lookups, put the items in a set (O(1)).","r":"Check every item = O(n).","g":["linear_search","big_o","time_complexity","z_algorithm","array","sorting"],"cat":"algo"},{"id":"ALG-46","t":"m","l":1,"q":"In a tree data structure, what is a leaf?","o":["The top node","A node with no children","Any node with two children","The connection between nodes"],"a":1,"e":"A tree is made of nodes connected parent → child, with no cycles.\n- Root: the single top node (no parent).\n- Children: nodes directly below a node.\n- Leaf: a node with no children.\n- Height: number of levels from root to the deepest leaf.\nExamples: folders on a disk, the HTML DOM, company org charts.","r":"Root at the top, leaves at the bottom (no children).","g":["tree","z_data_structure","html","dom"],"cat":"algo"},{"id":"ALG-47","t":"m","l":1,"q":"What is a graph in computer science?","o":["A chart with axes, used to plot data","A set of nodes (vertices) connected by edges","A sorted list of values with links","A type of loop that repeats over nodes"],"a":1,"e":"A graph models things and connections between them: cities and roads, users and friendships, web pages and links.\nEdges can be directed (one-way, like following someone) or undirected (two-way), and weighted (with a cost, like distance) or not.\nA tree is a special graph with no cycles.","r":"Graph = nodes + edges.","g":["graph","bfs","dfs","adjacency_list","dag","tree"],"cat":"algo"},{"id":"ALG-48","t":"m","l":1,"q":"What must be true before you can use binary search on a list?","o":["The list must have an even length","The list must be sorted","The list must contain only integers","The list must be smaller than 1000"],"a":1,"e":"Binary search decides which half to discard by comparing the target with the middle element. That only makes sense if smaller values are on the left and bigger values on the right, i.e. the list is sorted.\nOn an unsorted list it gives wrong answers. If you search many times, sorting once (O(n log n)) then searching (O(log n) each) can pay off.","r":"Binary search needs sorted data.","g":["binary_search","sorting","linear_search","time_complexity","array","z_algorithm"],"cat":"algo"},{"id":"ALG-49","t":"m","l":1,"q":"What is the time complexity of `nums[5]` on a Python list of 1 million items?","o":["O(1)","O(n)","O(log n)","O(5)"],"a":0,"e":"Lists are arrays, so the memory address of position 5 is calculated directly from where the list starts. It does not matter if the list has 10 or 10 million items.\nThat is constant time, written O(1). (O(5) is also 'constant', and Big-O drops constants, so we write O(1).)","r":"Index access on a list = O(1).","g":["array","big_o","time_complexity","index"],"cat":"algo"},{"id":"ALG-50","t":"m","l":0,"q":"What is an algorithm?","o":["A step-by-step procedure for solving a problem","A programming language used to write programs","A type of database used to store records","A kind of computer chip used in servers"],"a":0,"e":"An algorithm is a clear list of steps that always leads to a result. A cooking recipe is a good picture.\nExample: 'find the largest number in a list' = look at each number and remember the biggest seen so far.\nThe same problem can have several algorithms; some are much faster than others, which is why we study complexity (Big-O).","r":"Algorithm = a recipe for solving a problem.","g":["z_algorithm","z_data_structure","big_o","time_complexity","z_brute_force","sorting"],"fa":"A step-by-step procedure for solving a problem or doing a task","cat":"algo"},{"id":"ALG-51","t":"m","l":0,"q":"What is a data structure?","o":["A way to organize data, like a list, set or tree","A building plan for the rooms of a server farm","A password that protects the data of a database","A type of error that the compiler can raise"],"a":0,"e":"Data has to be arranged somehow in memory. Different arrangements make different operations fast or slow.\n- List/array: access by position is fast.\n- Dictionary (hash map): look up a value by key is fast.\n- Set: check membership and keep unique values.\n- Stack and queue: control the order in which items come out.\nChoosing the right data structure is half of solving most interview problems.","r":"Data structure = how data is organized in memory.","g":["z_data_structure","array","hash_table","tree","stack"],"fa":"A way of organizing and storing data so it can be used efficiently, such as a list, dictionary, set or tree","cat":"algo"},{"id":"ALG-52","t":"m","l":0,"q":"What is a dictionary (also called map or hash map)?","o":["A set of key-value pairs, looked up by key","An ordered list of numbers, accessed by position","A text file that contains a list of words","A sorting algorithm that is used for text"],"a":0,"e":"In a phone book you look up a name (key) and find a number (value). A dictionary works the same way.\nPython: `ages = {\"Ana\": 30, \"Luis\": 25}` and `ages[\"Ana\"]` returns 30. Java: `Map<String, Integer>` (`HashMap`).\nLooking up a key takes about the same time no matter how big the dictionary is (O(1) on average).","r":"Dictionary = key → value, fast lookup.","g":["dict","hash_table","hash","j_hashmap","z_java"],"fa":"A collection of key-value pairs where you look up a value by its key, like a phone book","cat":"algo"},{"id":"ALG-53","t":"m","l":0,"q":"What is special about a set?","o":["Stores each value once; fast membership checks","It always keeps its values in sorted order","It can only store numbers, never text values","It allows duplicates and keeps their order"],"a":0,"e":"A set is a collection with no duplicates. Adding the same value twice leaves one copy.\nPython: `s = {1, 2, 2, 3}` becomes {1, 2, 3}. Java: `HashSet`.\nIt is the usual tool for removing duplicates and for fast membership checks (`x in s` is O(1) on average, while in a list it is O(n)).","r":"Set = unique values + fast membership check.","g":["set","hash_table","n_hashset","z_java"],"fa":"It stores each value only once and checks 'is this in the set?' very quickly","cat":"algo"},{"id":"ALG-54","t":"m","l":0,"q":"What is a 'brute force' solution?","o":["A very fast and optimal solution to the problem","Trying every option: correct but often slow","A solution that needs special hardware to run","An attack that exists only in security work"],"a":1,"e":"Brute force means the straightforward approach without clever tricks. Example: to find two numbers that add up to a target, check every pair with two nested loops (O(n²)).\nIn interviews, it is a good first step: state the brute force solution and its cost, then improve it (for example with a hash map in O(n)).\n(In security, 'brute force' also names guessing passwords by trying many combinations.)","r":"Brute force = try everything. Start there, then improve.","g":["z_brute_force","big_o","hash","z_loop"],"fa":"Trying every possibility directly: simple and correct, but often too slow for big inputs","cat":"algo"},{"id":"ALG-55","t":"m","l":0,"q":"When we say an algorithm takes O(n) time, what is n?","o":["The input size, like the number of items","The number of lines of code in the program","The number of CPU cores that the machine has","The number of programmers on the dev team"],"a":0,"e":"Big-O describes how the work grows as the input grows. n is the input size.\nO(n) means that if the list becomes 10 times longer, the work becomes about 10 times bigger.\nO(n²) would be about 100 times bigger, and O(1) would stay the same.","r":"n = size of the input.","g":["big_o","time_complexity","space_complexity","linear_search","array","z_data_structure"],"fa":"The size of the input, for example the number of items in the list","cat":"algo"},{"id":"ALG-56","t":"m","l":0,"q":"What is the difference between sorting and searching?","o":["Sorting orders items; searching looks for one","They are the same operation under two names","Sorting deletes items; searching adds new ones","Searching only works on data that is sorted"],"a":0,"e":"Sorting: [3, 1, 2] becomes [1, 2, 3].\nSearching: is 2 in the list, and where? On an unsorted list you check items one by one (linear search, O(n)). On a sorted list you can use binary search (O(log n)).\nThis is why sorting first can pay off when you search many times.","r":"Sorting orders. Searching finds.","g":["sorting","linear_search","binary_search","z_algorithm","time_complexity","array","hash_table"],"fa":"Sorting puts the items in a defined order; searching finds a particular item (or checks if it exists)","cat":"algo"},{"id":"SD-01","t":"m","l":1,"q":"Horizontal vs vertical scaling?","o":["Horizontal: a bigger machine; vertical: more machines","Horizontal: more machines; vertical: a bigger one","They are the same thing under two different names","Vertical scaling needs a load balancer to work"],"a":1,"e":"Vertical scaling (scale up): give one server more CPU, RAM or disk. Simple, no code changes, but there is a maximum size and that one server is still a single point of failure.\nHorizontal scaling (scale out): add more servers and spread the traffic with a load balancer. It can grow much further and survives a server dying, but the app must be designed for it (e.g. stateless servers).","r":"Vertical = bigger machine. Horizontal = more machines.","g":["vertical_scaling","horizontal_scaling","load_balancer","n_cpu","n_ram","spof"],"fa":"Horizontal: add more machines; vertical: add CPU/RAM to one machine","cat":"sys"},{"id":"SD-02","t":"m","l":2,"q":"Requests have very different durations (some take seconds). Which load balancing strategy adapts best?","o":["Round robin: send requests in a fixed rotation","Least connections: pick the least busy server","Random choice: pick any server for each request","DNS only: one record for each of the servers"],"a":1,"e":"Round robin sends requests in turn: server 1, 2, 3, 1, 2, 3... That is fair only if every request costs about the same.\nIf some requests take seconds, one server can pile up slow requests while it keeps receiving its 'turn'.\nLeast connections sends each new request to the server that is currently handling the fewest, so busy servers naturally get less.","r":"Uneven request costs → least connections.","g":["load_balancer","high_availability","latency","reverse_proxy","horizontal_scaling"],"fa":"Least connections","cat":"sys"},{"id":"SD-03","t":"m","l":1,"q":"What does a CDN mainly provide?","o":["A database replica that is placed near users","Caching content near users, cutting latency","Rendering the pages on the server for SEO","Authentication of users before each request"],"a":1,"e":"A CDN (Content Delivery Network) has servers in many cities around the world. It keeps copies of your static files (images, JS, CSS, videos) near your users.\nA user in Lima downloads from a nearby CDN server instead of your server in Europe: faster for them, less load for you.\nUse versioned file names (`app.3f2a.js`) so new deploys are picked up.","r":"CDN = copies of static content close to users.","g":["cdn","cache","latency","origin","z_server","css"],"fa":"Caching content at edge locations close to users, reducing latency and origin load","cat":"sys"},{"id":"SD-04","t":"m","l":2,"q":"In the cache-aside (lazy loading) pattern, who populates the cache?","o":["The database itself fills the cache by itself","The app: on a miss, read the DB and set the cache","A nightly batch job that preloads all the keys","The CDN fills the cache on every single request"],"a":1,"e":"Cache-aside steps: 1) the app asks the cache; 2) if found (hit), use it; 3) if not (miss), read from the database and store the result in the cache with a TTL (expiry time).\nOnly data that is actually requested gets cached.\nDownsides: the first request is slow, and cached data can be outdated until it expires or you delete it on update.","ec":"def get_user(uid):\n    user = cache.get(f\"user:{uid}\")\n    if user is None:                       # miss\n        user = db.load_user(uid)\n        cache.set(f\"user:{uid}\", user, ttl=300)\n    return user","r":"Cache-aside: check cache → on miss load DB → store in cache.","g":["cache_aside","cache","ttl","sp_lazy_loading"],"fa":"The application: on a miss it reads the DB, then writes the value into the cache","cat":"sys"},{"id":"SD-05","t":"m","l":2,"q":"Write-through caching means…","o":["Writes go to the cache only and never reach the DB","Every write updates the cache and the database together","Writes skip the cache and go straight to the DB","The cache is cleared on every write"],"a":1,"e":"With write-through, every time data is saved, the app writes it to the cache AND the database together.\nThe cache is always up to date, so reads are fresh. The cost is slower writes (two places).\nWrite-back (write-behind) writes to the cache first and to the database later: faster, but data can be lost if the cache crashes.","r":"Write-through = write to cache and DB together.","g":["write_through","cache","cache_aside","ttl","consistency","latency"],"fa":"Every write updates the cache and the database synchronously","cat":"sys"},{"id":"SD-06","t":"m","l":3,"q":"A popular cache key expires and thousands of requests hit the DB at once. This is…","o":["Cache stampede (thundering herd)","Split brain between two nodes","Hot partition on one shard","Replication lag on a read replica"],"a":0,"e":"While the key was cached, the database was protected. The moment it expires, every request misses at the same time and all of them query the database to rebuild the same value, which can overload it.\nFixes: let only one request rebuild it (a lock) while others wait or get the old value; refresh shortly before expiry; add random jitter to TTLs so keys don't all expire together.","r":"Many misses at once on a hot key = cache stampede.","g":["cache_stampede","cache","ttl","rate_limit","spof","load_balancer"],"cat":"sys"},{"id":"SD-07","t":"m","l":2,"q":"According to the CAP theorem, during a network partition a distributed system must choose between…","o":["Cost and performance","Consistency and availability","Latency and throughput","Caching and persistence"],"a":1,"e":"A network partition is when servers of one system cannot talk to each other (cables, data centers, outages). In real networks this will happen.\nDuring it, a server that receives a request must either refuse to answer until it can confirm the latest data (choose Consistency) or answer with what it has, possibly outdated (choose Availability).\nBanks lean to consistency; social feeds lean to availability.","r":"During a partition: correct-or-nothing (C) vs answer-anyway (A).","g":["cap","consistency","availability","partition"],"cat":"sys"},{"id":"SD-08","t":"m","l":3,"q":"Why use consistent hashing to distribute keys across cache nodes?","o":["It encrypts the keys that are stored in the cache","A node change remaps only about 1/N of the keys","It guarantees perfect balance without virtual nodes","It removes the need for replication entirely"],"a":1,"e":"With `hash(key) % N`, adding one server changes N, so almost every key suddenly maps to a different server: the whole cache is effectively lost.\nConsistent hashing places servers and keys on a circle; each key goes to the next server clockwise. Adding a server only takes over the keys between it and its neighbor, about 1/N of them.\n'Virtual nodes' (several points per server) spread the load evenly.","r":"Consistent hashing = adding a node moves few keys.","g":["consistent_hashing","sharding","cache","hash_table","horizontal_scaling","partition"],"fa":"Adding or removing a node remaps only about 1/N of keys instead of nearly all","cat":"sys"},{"id":"SD-09","t":"m","l":3,"q":"Key difference between Kafka and a traditional queue like RabbitMQ?","o":["Kafka cannot keep the messages after delivery","Kafka is a durable log; consumers replay by offset","RabbitMQ is only used for application logging","There is no difference between the two systems"],"a":1,"e":"RabbitMQ: a message waits in a queue until a consumer takes and acknowledges it; then it is gone. Great for distributing tasks to workers.\nKafka: messages are appended to a log that is kept for days. Each consumer remembers its position (offset), so it can re-read old messages, and many different services can read the same stream independently.\nKafka fits high-volume event streams; order is guaranteed only within a partition.","r":"RabbitMQ = task queue. Kafka = replayable event log.","g":["kafka","message_queue","broker","pub_sub","delivery_semantics","high_availability","partition"],"fa":"Kafka is a durable, partitioned log; consumers track offsets and can replay, and many consumer groups read the same stream","cat":"sys"},{"id":"SD-10","t":"m","l":3,"q":"A message broker guarantees at-least-once delivery. What must consumers do?","o":["Nothing, since each message arrives only once","Be idempotent: dedupe by ID or repeat safely","Always switch the broker to exactly-once mode","Acknowledge the message before processing it"],"a":1,"e":"'At-least-once' means a message is never lost, but it may arrive twice. For example, the consumer processed it but crashed before confirming, so the broker sends it again.\nSo processing the same message twice must be harmless: store processed message IDs and skip repeats, or use operations like 'set status = paid' instead of 'add 10 €'.\nConfirming before processing would risk losing messages instead.","r":"At-least-once delivery → idempotent consumers.","g":["delivery_semantics","idempotent","message_queue","broker"],"fa":"Be idempotent (deduplicate by message ID or make operations naturally repeatable)","cat":"sys"},{"id":"SD-11","t":"m","l":2,"q":"A 6-person startup with one product debates microservices. The strongest argument against starting with them?","o":["Microservices cannot scale beyond a few nodes","Operational overhead: network failures, deploys","They require Java as the only possible language","They are not cloud-native by their very design"],"a":1,"e":"Microservices split an app into many small services that talk over the network. That brings real costs: many deployments and pipelines, network errors and timeouts, debugging across services, and keeping data consistent without one shared transaction.\nA small team usually moves faster with a well-organized monolith (one app with clear internal modules), and extracts services later when scale or team size justifies it.","r":"Start with a modular monolith; split when there is a real reason.","g":["microservices","monolith","api_gateway","observability","horizontal_scaling","failover"],"fa":"Operational overhead: distributed debugging, network failures, deployments, data consistency across services","cat":"sys"},{"id":"SD-12","t":"m","l":2,"q":"Which is a typical responsibility of an API gateway?","o":["Running database migrations on every deployment","One entry point: routing, auth, rate limiting, TLS","Storing the data of the users of the app","Compiling the frontend assets for the browser"],"a":1,"e":"With many backend services, clients would need to know every address and every service would repeat auth and rate limiting.\nAn API gateway sits in front: clients call one address, and the gateway checks authentication, applies rate limits, terminates HTTPS and routes each request to the right service.\nKeep business logic out of it, or it becomes a bottleneck.","r":"API gateway = one front door for many services.","g":["api_gateway","microservices","rate_limit","api","tls","authn"],"fa":"A single entry point handling routing, auth, rate limiting, TLS termination and request aggregation","cat":"sys"},{"id":"SD-13","t":"m","l":3,"q":"A downstream service is failing and timing out. Which pattern stops your service from hammering it and failing slowly?","o":["Circuit breaker","Singleton","Saga","Sharding"],"a":0,"e":"Like an electrical breaker: after several failures in a row, the circuit 'opens' and calls to that service fail immediately (or return a fallback) instead of waiting for timeouts.\nThis protects your own threads and gives the broken service time to recover. After a pause, the breaker lets a test request through ('half-open'); if it works, it closes again.\nCombine with timeouts and retries with exponential backoff.","r":"Circuit breaker = stop calling a failing service for a while.","g":["circuit_breaker","retry_backoff","failover","latency","high_availability","rate_limit"],"cat":"sys"},{"id":"SD-14","t":"m","l":2,"q":"In leader-follower (primary-replica) replication, where do writes go?","o":["Any replica can accept writes at any moment","Only the leader; followers copy it and serve reads","Only the followers accept writes, then sync","Writes are sent round robin to all the nodes"],"a":1,"e":"One server, the leader (primary), accepts all writes. It sends every change to the followers (replicas), which keep copies and can answer read queries.\nHaving one writer avoids conflicts. If the leader dies, one follower is promoted to be the new leader (failover).","r":"Writes → leader. Reads → leader or followers.","g":["leader_follower","replication","failover","high_availability","read_replica","consistency"],"fa":"Only the leader; followers replicate and serve reads","cat":"sys"},{"id":"SD-15","t":"m","l":2,"q":"1M daily active users each make 10 requests per day. Average QPS?","o":["~12","~116","~1,160","~11,600"],"a":1,"e":"Total requests per day: 1,000,000 × 10 = 10,000,000.\nA day has 86,400 seconds (round to 100,000 for quick math).\n10,000,000 / 86,400 ≈ 116 queries per second on average.\nTraffic is not flat: assume peaks of 2 to 10 times the average when sizing the system.","r":"QPS ≈ requests per day / 100,000.","g":["qps","latency","throughput","horizontal_scaling","load_balancer"],"cat":"sys"},{"id":"SD-16","t":"m","l":2,"q":"Why keep application servers stateless?","o":["To save disk space on every application server","Any instance can serve any request (easy scaling)","Stateless servers are faster for CPU-heavy work","To avoid using a database anywhere in the system"],"a":1,"e":"If a server keeps user data in its own memory (like a login session), that user must always hit the same server, and if it restarts, the data is lost.\nStateless servers keep nothing between requests: sessions go to Redis or a signed token, files go to object storage (S3).\nThen any server can handle any request, and you can add or remove servers freely.","r":"Keep state out of app servers.","g":["stateless","horizontal_scaling","object_storage","autoscaling","failover","redis"],"fa":"Any instance can handle any request, enabling autoscaling and easy failover; session state lives in a shared store or token","cat":"sys"},{"id":"SD-17","t":"m","l":3,"q":"CQRS means…","o":["Caching Queries Reduces Storage, a caching rule","Separating the write model from the read model","A query language used by relational databases","A consensus algorithm for distributed nodes"],"a":1,"e":"Command Query Responsibility Segregation: use one model to change data (commands, with all validation) and a different model, shaped for fast reading, to query it.\nExample: orders are written to PostgreSQL; an event updates a denormalized search index used by the order list page.\nThe read side may be a little behind (eventual consistency). It adds complexity, so use it only when reads and writes really differ.","r":"CQRS = separate models for writing and reading.","g":["cqrs","eventual_consistency","denormalization","message_queue","microservices","pub_sub"],"fa":"Separating the write model (commands) from the read model (queries), often with different data stores","cat":"sys"},{"id":"SD-18","t":"m","l":2,"q":"The three pillars of observability are…","o":["CPU, RAM, disk","Logs, metrics, traces","Unit, integration, E2E tests","Dev, staging, prod"],"a":1,"e":"- Metrics: numbers over time (requests per second, error rate, latency). They tell you THAT something is wrong and trigger alerts.\n- Traces: the path of one request across services, with timing per step. They show WHERE the time or error is.\n- Logs: detailed text events. They tell you WHY.\nOpenTelemetry is the common standard to produce all three.","r":"Metrics = that, traces = where, logs = why.","g":["observability","logs","sli_slo_sla","latency","throughput","z_monitoring"],"cat":"sys"},{"id":"SD-19","t":"m","l":2,"q":"A 99.9% monthly availability SLO allows roughly how much downtime per 30-day month?","o":["~4.3 minutes","~43 minutes","~7.2 hours","~1 day"],"a":1,"e":"30 days = 43,200 minutes. 0.1% of that is about 43 minutes of allowed downtime per month.\nEach extra 9 divides it by 10: 99.99% ≈ 4.3 minutes per month.\nVocabulary: SLI = what you measure (e.g. % successful requests); SLO = your internal target; SLA = a contract promise to customers, with penalties.","r":"99.9% ≈ 43 min/month; 99.99% ≈ 4 min/month.","g":["sli_slo_sla","availability","high_availability","failover","spof","observability"],"cat":"sys"},{"id":"SD-20","t":"m","l":2,"q":"A chat app needs the server to push messages instantly to clients. Most suitable transport?","o":["Polling the server every 30 seconds","WebSockets (or Server-Sent Events for one-way push)","SMTP, the protocol for email delivery","Plain HTTP/1.0 with a new connection each time"],"a":1,"e":"Normal HTTP only lets the client ask; the server cannot speak first. Polling ('any news?') every few seconds is wasteful and slow.\nA WebSocket keeps one connection open, and both sides can send messages at any time, with very low delay.\nServer-Sent Events are a simpler option when only the server needs to push (e.g. live scores).","r":"Real-time two-way → WebSockets.","g":["websocket","polling","latency","http"],"cat":"sys"},{"id":"SD-21","t":"m","l":2,"q":"Blue-green deployment means…","o":["Deploying only on weekends, in a quiet time slot","Two identical environments; switch traffic at once","Deploying to 1% of users first, then growing it","Using two programming languages in one service"],"a":1,"e":"Blue runs the current version and receives all traffic. You deploy the new version to green and test it there.\nThen you switch the load balancer from blue to green in one step. If something breaks, switch back instantly.\nA canary release is different: it sends a small percentage of users to the new version first and increases it gradually.","r":"Blue-green = two environments, flip traffic, flip back if needed.","g":["blue_green","canary","load_balancer","rollback"],"fa":"Running two identical environments and switching traffic from the old (blue) to the new (green) at once, with instant rollback","cat":"sys"},{"id":"SD-22","t":"f","l":2,"q":"What framework do you follow in a 45-minute system design interview?","a":"1. Clarify requirements: functional (core features only) and non-functional (scale, latency, availability, consistency). ~5 min.\n2. Estimate: users, QPS, storage, read/write ratio.\n3. Define the API and the data model.\n4. High-level design: clients, load balancer, services, database, cache, queues, storage.\n5. Deep dive into 1-2 components the interviewer cares about (bottlenecks, scaling, partitioning).\n6. Trade-offs, failure modes, monitoring, and what you would improve with more time.\n- Think aloud, draw boxes, state assumptions, check in with the interviewer.","g":["qps","load_balancer","cache","api"],"cat":"sys"},{"id":"SD-23","t":"f","l":2,"q":"Design a URL shortener (like bit.ly).","a":"- Requirements: shorten, redirect, optional custom alias and expiry; read-heavy (e.g. 100 reads per write).\n- API: `POST /urls {long_url}` → short code; `GET /{code}` → 301/302 redirect (302 if you want click analytics).\n- Code generation: base62 of a unique ID (DB sequence or Snowflake-style IDs); 7 characters ≈ 3.5 trillion codes. Or hash + collision check.\n- Storage: key-value table `code → long_url, created_at, expires_at`.\n- Cache popular codes in Redis; redirects at the edge/CDN.\n- Analytics as async events to a queue.\n- Abuse: rate limits, malicious URL scanning.","g":["cache","message_queue","rate_limit","redis","http_method","api","cdn"],"cat":"sys"},{"id":"SD-24","t":"f","l":3,"q":"Design a rate limiter for an API.","a":"- Where: API gateway or middleware; key by user ID, API key or IP.\n- Algorithms: token bucket (allows bursts), leaky bucket (smooth), fixed window (simple, edge spikes), sliding window (accurate).\n- Shared counters in Redis with atomic operations (INCR + EXPIRE, or a Lua script).\n- Response: 429 + `Retry-After` and remaining-quota headers.\n- If Redis is down: fail open (allow) or fail closed (block)? Decide per endpoint.\n- Several tiers (per second and per day), per-endpoint limits, a local in-memory pre-check to reduce Redis load.","g":["rate_limit","redis","api_gateway","api","sliding_window","n_token_bucket","n_retry_after","middleware"],"cat":"sys"},{"id":"SD-25","t":"f","l":3,"q":"Design a chat application (like WhatsApp).","a":"- Features: 1:1 and group messages, online status, delivered/read receipts, history, offline delivery.\n- Clients keep WebSocket connections to chat servers; a session service maps user → server.\n- Send flow: message → server → persist (partitioned by conversation, ordered by time/ID) → route to the recipient's server via pub/sub → push; if offline, push notification and deliver on reconnect.\n- Message IDs per conversation for ordering and deduplication (client retries).\n- Groups: fan-out on write for small groups.\n- Presence with heartbeats and TTLs; media in object storage + CDN; mention end-to-end encryption.","g":["websocket","pub_sub","object_storage","cdn","encryption"],"cat":"sys"},{"id":"SD-26","t":"f","l":3,"q":"Design a news feed (like the Twitter/X home timeline).","a":"- Posting: store the post; publish an event.\n- Fan-out on write (push): add the post ID to each follower's cached timeline (Redis lists). Fast reads, expensive for celebrities with millions of followers.\n- Fan-out on read (pull): merge followed users' recent posts when the timeline is opened. Cheap writes, slower reads.\n- Hybrid: push for normal users, pull for celebrities at read time.\n- Timelines store IDs; load post and user details from caches.\n- Ranking service, cursor pagination, media via CDN, counters updated asynchronously.","g":["cache","redis","pagination","cdn"],"cat":"sys"},{"id":"SD-27","t":"f","l":3,"q":"Design a file storage and sync service (like Dropbox).","a":"- Split files into chunks (e.g. 4 MB) and hash each chunk; upload only changed chunks (deduplication, resumable uploads).\n- Chunks in object storage (S3); a metadata database stores files, versions, chunk lists and permissions.\n- Upload directly to storage with pre-signed URLs.\n- Sync: clients keep a cursor; a notification service (long polling / WebSocket) announces changes; clients pull new metadata.\n- Conflicts: keep both copies, or version history.\n- Sharing with ACLs and links; CDN for downloads; encryption at rest.","g":["object_storage","cdn","websocket","encryption","polling","s3"],"cat":"sys"},{"id":"SD-28","t":"f","l":3,"q":"Design a notification system (email, SMS, push).","a":"- Other services call a Notification API with user, template and data.\n- Validate, check user preferences/opt-outs and rate limits, render the template.\n- One queue per channel (email, SMS, push) so a slow provider does not block the others.\n- Workers call providers (SES, Twilio, FCM/APNs) with retries, exponential backoff and a dead-letter queue.\n- Idempotency keys to avoid duplicates; track delivery status.\n- Priority queues: critical messages (OTP codes) before marketing.","g":["message_queue","retry_backoff","idempotent","api"],"cat":"sys"},{"id":"SD-29","t":"f","l":2,"q":"Design a parking lot system (object-oriented design).","a":"- Clarify: levels, spot types (motorcycle, compact, large, EV), payment, entry/exit gates.\n- Classes: `ParkingLot` (levels, gates), `Level` (spots), `ParkingSpot` (type, is_free), `Vehicle` with a size, `Ticket` (spot, entry time), `PricingStrategy`.\n- Spot assignment strategy (nearest free, by type) behind an interface.\n- Concurrency: two cars must never get the same spot (lock or atomic DB update).\n- Show SOLID: pricing as a Strategy, free-spot displays as Observers.","g":["strategy","observer","solid","z_oop","interface","design_pattern","class","inheritance","polymorphism"],"cat":"sys"},{"id":"SD-30","t":"f","l":3,"q":"Design a distributed job scheduler (run tasks at a given time or on a cron).","a":"- API to create jobs: schedule, payload, retry policy.\n- Store jobs in a database indexed by `next_run_at`.\n- Scheduler instances find due jobs and claim them atomically (`SELECT ... FOR UPDATE SKIP LOCKED` or leases), then push them to a queue.\n- Workers run them, report status, retry with backoff, and send to a dead-letter queue after N failures.\n- Execution is at-least-once, so jobs must be idempotent.\n- Partitioning or leader election to scale schedulers; heartbeats to recover jobs from dead workers; per-job monitoring.","g":["message_queue","delivery_semantics","idempotent","worker","api"],"cat":"sys"},{"id":"SD-31","t":"m","l":1,"q":"What does a load balancer do?","o":["It stores the data of the application itself","Spreads requests over servers, skipping sick ones","It compresses images before sending them out","It writes the logs that the application emits"],"a":1,"e":"A load balancer sits in front of a group of identical servers. Clients talk to its single address; it forwards each request to one of the servers.\nThis spreads the work, lets you add servers as traffic grows, and keeps the site up if one server fails: health checks detect it and stop sending it traffic.\nExamples: Nginx, HAProxy, AWS ALB.","r":"Load balancer = traffic distributor + health checks.","g":["load_balancer","horizontal_scaling","z_server","n_aws","n_alb_nlb"],"fa":"Distributes incoming requests across several servers and stops sending traffic to unhealthy ones","cat":"sys"},{"id":"SD-32","t":"m","l":1,"q":"Why does a cache make reads faster?","o":["It compresses the database to make it smaller","Hot data sits in fast storage, skipping slower work","It deletes old rows from the main database","It encrypts the data before it is read back"],"a":1,"e":"Reading from memory takes microseconds; a database query or an external API call can take milliseconds or more.\nA cache stores results you already computed or fetched, so the next request gets them instantly.\nThe hard part is freshness: cached data can be outdated, so entries get an expiry time (TTL) or are deleted when the data changes.","r":"Cache = fast copy of data you will need again.","g":["cache","ttl","latency","z_database","api"],"fa":"It keeps copies of frequently used data in fast storage (usually memory), so you skip slower work like a database query","cat":"sys"},{"id":"SD-33","t":"m","l":1,"q":"In the client-server model, which is true?","o":["The server always starts the communication first","Clients send requests; servers process and respond","Clients store all the data of the whole system","There is only ever one client at any one time"],"a":1,"e":"The client is the program the user interacts with (a browser, a phone app). The server is a program on another machine that holds data and business logic.\nThe client sends a request ('give me my orders'); the server checks permissions, reads the database and returns a response.\nOne server usually handles many clients at the same time.","r":"Client asks, server answers.","g":["client_server","http","z_server","z_database"],"fa":"Clients (browser, mobile app) send requests; servers process them and send responses","cat":"sys"},{"id":"SD-34","t":"m","l":1,"q":"Latency vs throughput?","o":["They are the same thing, measured two ways","Latency: time of one request; throughput: rate","Latency is measured in megabytes per second","Throughput is the rate of errors in a system"],"a":1,"e":"Picture a highway. Latency is how long one car takes to travel from A to B. Throughput is how many cars pass per hour.\nYou can have high throughput with high latency (a big batch job) or low latency with low throughput.\nFor APIs, latency is usually reported as percentiles: p50 (typical), p99 (the slowest 1%).","r":"Latency = time per request. Throughput = requests per second.","g":["latency","throughput","qps","z_bottleneck","horizontal_scaling","cache"],"fa":"Latency = how long one request takes; throughput = how many requests are handled per unit of time","cat":"sys"},{"id":"SD-35","t":"m","l":1,"q":"Monolith vs microservices?","o":["A monolith is always the worse design choice","A monolith deploys as one; microservices apart","Microservices share one database by definition","They are two different programming languages"],"a":1,"e":"Monolith: all features (users, orders, payments) live in one codebase and are deployed together. Simple to develop, test and deploy at first.\nMicroservices: each feature area is its own small app with its own deployment (and often its own database), communicating via HTTP or messages. Teams can work and scale independently, at the cost of much more operational complexity.","r":"Monolith = one app. Microservices = many small apps.","g":["monolith","microservices","http","z_database","z_deploy"],"fa":"A monolith is one deployable application; microservices are many small services deployed independently that talk over the network","cat":"sys"},{"id":"SD-36","t":"m","l":1,"q":"Why put a message queue between an order service and an email service?","o":["To make the emails arrive much faster to users","To decouple them; emails are handled later","Queues replace the need for a real database","To encrypt each email that is being sent out"],"a":1,"e":"Without a queue, the order service calls the email service directly and must wait; if the email service is down, the order request fails.\nWith a queue (RabbitMQ, SQS, Kafka) the order service just publishes 'order created' and responds to the user immediately. The email service reads messages at its own pace and catches up after outages.\nThis is asynchronous communication.","r":"Queue = decouple producer and consumer; work happens later.","g":["message_queue","broker","queue","sqs_sns","kafka"],"fa":"To decouple them: the order service drops a message and continues; the email service processes it when it can, even if it was briefly down","cat":"sys"},{"id":"SD-37","t":"m","l":1,"q":"What does DNS do?","o":["It encrypts the traffic between browser and server","It maps a domain name to a server IP address","It stores the files that make up the website","It balances the CPU load across the servers"],"a":1,"e":"Computers connect using IP addresses (e.g. 93.184.216.34), but people remember names.\nDNS (Domain Name System) works like the internet's phone book: your device asks a DNS resolver 'what is the IP of example.com?' and gets the address back. Results are cached for a while (TTL).\nDNS can also route users to nearby servers.","r":"DNS = name → IP address.","g":["dns","n_ip","z_server","ttl"],"fa":"Translates a domain name like example.com into the IP address of a server","cat":"sys"},{"id":"SD-38","t":"m","l":1,"q":"What is a single point of failure (SPOF)?","o":["A bug that is found in a single line of code","A component whose failure takes the system down","The first server that is set up in a cluster","A failed test somewhere in the build pipeline"],"a":1,"e":"If your app runs on one server with one database, and that database crashes, everything stops: it is a single point of failure.\nYou remove SPOFs with redundancy: several app servers behind a load balancer, a database with a replica ready to take over, more than one data center.\nHigh availability is designed by removing SPOFs.","r":"SPOF = one part that takes everything down. Add redundancy.","g":["spof","high_availability","component","load_balancer","z_server"],"fa":"A component whose failure brings the whole system down because there is no backup","cat":"sys"},{"id":"SD-39","t":"m","l":1,"q":"What is the main purpose of running several copies (replicas) of a service or database?","o":["To save money on the cost of infrastructure","High availability: if one copy fails, others serve","To make the code of the service much shorter","To avoid the need to make any backups at all"],"a":1,"e":"Machines and networks fail. With only one copy, any failure means downtime.\nReplicas keep the system running when one dies (failover), and they can share read traffic.\nReplicas are not backups: if someone deletes data by mistake, the deletion is copied to every replica too. You still need backups.","r":"Replicas = availability. Backups = recovery from mistakes.","g":["replication","high_availability","failover","availability","z_database"],"fa":"High availability: if one copy fails, others keep serving; reads can also be spread across copies","cat":"sys"},{"id":"SD-40","t":"m","l":1,"q":"What is a reverse proxy (e.g. Nginx in front of your app)?","o":["A proxy that hides the client from websites it visits","A server in front of the app that forwards requests","A browser extension that rewrites requests it sends","A database driver that is written for proxy servers"],"a":1,"e":"Clients connect to the reverse proxy, not directly to your app. It forwards each request to the app server(s) and returns the response.\nIt can terminate HTTPS, serve static files, compress responses, cache, limit rates and balance load.\nA forward proxy is the opposite: it acts on behalf of clients (e.g. a company proxy for employees' browsing).","r":"Reverse proxy = front door in front of your servers.","g":["reverse_proxy","load_balancer","tls","z_server","https"],"fa":"A server in front of your application servers that receives client requests and forwards them, often handling TLS, compression, caching and load balancing","cat":"sys"},{"id":"SD-41","t":"m","l":0,"q":"What is 'system design'?","o":["Choosing the main components and how they connect","Drawing the screens of the user interface of an app","Writing unit tests for the code of the application","Installing an operating system on all the servers"],"a":0,"e":"Coding solves a problem inside one program. System design decides the big picture: which parts exist, what each one does, how they talk, where the data lives and what happens when something fails or traffic grows.\nIn interviews you draw boxes and arrows (clients, load balancer, services, database, cache, queue) and explain your choices.","r":"System design = the big picture of components and connections.","g":["z_system_design","component","load_balancer","z_database","z_server"],"fa":"Choosing the main components of a software system (servers, databases, caches, queues) and how they connect so it works reliably at scale","cat":"sys"},{"id":"SD-42","t":"m","l":0,"q":"What does it mean when a system 'scales'?","o":["It handles more users or data by adding resources","It becomes smaller in size as it keeps growing","It is written with fewer lines of code overall","It is used by only a small number of people"],"a":0,"e":"A scalable system keeps working well when load grows from 100 users to 100,000.\nYou can scale vertically (a bigger machine) or horizontally (more machines).\nA system that works for 10 users but collapses at 1,000 does not scale.","r":"Scalable = still works when load grows.","g":["vertical_scaling","horizontal_scaling","z_bottleneck","load_balancer","high_availability","cache","z_system_design"],"fa":"It can handle more users or data by adding resources, without breaking or becoming too slow","cat":"sys"},{"id":"SD-43","t":"m","l":0,"q":"What is a bottleneck?","o":["The slowest part of a system, limiting the whole","A type of firewall that blocks incoming traffic","The first server that is set up in a cluster","A security hole that is found in the system"],"a":0,"e":"Like the narrow neck of a bottle, the narrowest part decides how fast everything can flow.\nExample: 20 application servers that all wait for one overloaded database. The database is the bottleneck, and adding more app servers will not help.\nPerformance work begins with measuring to find the real bottleneck.","r":"Bottleneck = the part that limits the whole system.","g":["z_bottleneck","throughput","z_server","z_database"],"fa":"The slowest part of a system, which limits the speed of the whole thing","cat":"sys"},{"id":"SD-44","t":"m","l":0,"q":"High-level design vs low-level design?","o":["High-level: components; low-level: internal classes","They are the same thing under two different names","High-level design means a more expensive system","Low-level design means writing assembly code only"],"a":0,"e":"High-level design (HLD): boxes and arrows. Which services exist? Where is the data stored? Where is a cache or a queue used?\nLow-level design (LLD): inside a box. Which classes and interfaces? What methods and fields? Which design patterns?\n'Design a URL shortener' is usually HLD. 'Design a parking lot' is usually LLD (object-oriented design).","r":"HLD = components. LLD = classes and methods.","g":["z_system_design","z_oop","design_pattern","component","z_database","z_url"],"fa":"High-level: the big components and how they interact (services, databases, queues); low-level: what happens inside one component (classes, methods, data models)","cat":"sys"},{"id":"SD-45","t":"m","l":0,"q":"Why do interviewers want you to talk about trade-offs in a design?","o":["Every choice has costs; weighing them shows judgment","There is always a single perfect answer to find","It makes the interview last longer than planned","Trade-offs are only about the money of the project"],"a":0,"e":"There is rarely a best design, only a best design for these requirements.\nExamples: a cache makes reads faster but data may be stale. A microservice split gives independence but adds network failures. SQL gives strong consistency; some NoSQL stores give easier horizontal scaling.\nSay: 'I choose X because of Y, and the cost is Z'.","r":"Say what you choose, why, and what it costs.","g":["z_trade_off","horizontal_scaling","nosql","sql","cache"],"fa":"Because every choice has benefits and costs (speed vs consistency, simplicity vs flexibility); showing that you weigh them proves engineering judgment","cat":"sys"},{"id":"SD-46","t":"m","l":0,"q":"In a typical web system, which path does a user request usually follow?","o":["Browser, DNS, load balancer, app server, database","Database, then browser, then server, and back again","Server, then CDN, then printer, then the browser","Browser directly to the database, and nothing else"],"a":0,"e":"1. The browser asks DNS for the IP address of the site.\n2. The request reaches a load balancer, which picks one application server.\n3. The application server runs the business logic and queries the database (or a cache).\n4. The response travels back the same way.\nThe browser never talks to the database directly, because that would be insecure.","r":"Browser → load balancer → app server → database.","g":["dns","load_balancer","client_server","z_database","z_server","n_ip"],"fa":"Browser → (DNS, load balancer) → application server → database → response back to the browser","cat":"sys"},{"id":"SEC-01","t":"m","l":1,"q":"Which is the correct primary defense against SQL injection?","o":["Escaping the quotes in the user input by hand","Parameterized queries or prepared statements","Hiding detailed error messages from the users","Using POST requests instead of GET requests"],"a":1,"e":"SQL injection happens when user input is glued into SQL text, so a clever input changes the query itself (e.g. `' OR 1=1 --` returns all rows, or `'; DROP TABLE users; --`).\nWith parameterized queries, the SQL and the values are sent separately; the database never runs the input as code.\nManual escaping is easy to get wrong. Also give the app's DB user only the permissions it needs.","r":"Never build SQL with string formatting; use parameters.","g":["sql_injection","least_privilege","sql","orm","d_ddl_dml"],"fa":"Parameterized queries / prepared statements (or an ORM that uses them)","cat":"sec"},{"id":"SEC-02","t":"m","l":2,"q":"A comment containing `<script>` is saved and later shown to other users, running in their browsers. This is…","o":["Reflected XSS","Stored XSS","CSRF","SSRF"],"a":1,"e":"XSS (Cross-Site Scripting) means an attacker gets their JavaScript to run on your site, in other users' browsers. That script can steal data or act as the user.\nStored XSS: the malicious script is saved in your database (a comment, a profile name) and served to everyone who views it. Reflected XSS: it comes from a URL parameter and is echoed back once.\nDefense: escape output (templates like Jinja and React do it by default), sanitize any HTML you allow, and add a Content-Security-Policy.","r":"Stored XSS = malicious script saved and shown to others. Escape output.","g":["xss","csp","javascript","react","html","d_view"],"cat":"sec"},{"id":"SEC-03","t":"m","l":2,"q":"CSRF attacks work because…","o":["Passwords are weak and easy for bots to guess","Browsers attach cookies to cross-site requests","HTTPS is missing on the target site entirely","The API uses JSON bodies instead of form data"],"a":1,"e":"You are logged in to bank.com, so your browser has its session cookie. You visit evil.com, which secretly submits a form to bank.com/transfer. Your browser adds the bank cookie automatically, so the bank thinks YOU sent it.\nThat is CSRF (Cross-Site Request Forgery).\nDefenses: `SameSite=Lax` or `Strict` cookies, anti-CSRF tokens in forms, checking the `Origin` header, and never changing data with GET.","r":"CSRF = another site uses your logged-in cookies. Use SameSite + CSRF tokens.","g":["csrf","cookie","session","http_method"],"fa":"Browsers automatically attach cookies to cross-site requests, so a malicious page can trigger authenticated actions","cat":"sec"},{"id":"SEC-04","t":"m","l":1,"q":"How should user passwords be stored?","o":["Encrypted with AES using a key kept in the app","Hashed once with SHA-256 and then stored as is","Hashed with a slow salted function: Argon2id, bcrypt","Stored in plain text inside a protected database"],"a":2,"e":"Store passwords so that even if the database is stolen, the attacker cannot get them back.\nEncryption is reversible: whoever finds the key gets every password. Fast hashes like SHA-256 can be guessed billions of times per second on GPUs.\nPassword hashing functions (Argon2id, bcrypt, scrypt) are deliberately slow and add a random salt, making guessing extremely expensive. To log in, hash the attempt and compare.","r":"Passwords → Argon2id or bcrypt. Never plain, never just SHA-256.","g":["password_hashing","salt","hashing","encryption","n_sha"],"fa":"Hashed with a slow, salted password hashing function: Argon2id, bcrypt or scrypt","cat":"sec"},{"id":"SEC-05","t":"m","l":2,"q":"What is the purpose of a salt in password hashing?","o":["To encrypt the final hash before it is stored away","Equal passwords hash differently (stops rainbow tables)","To make the hashing function run faster on each login","To replace the need for multi-factor authentication"],"a":1,"e":"A salt is a random value generated for each user and mixed into the password before hashing. It is stored next to the hash; it does not need to be secret.\nWithout salts, everyone with password '123456' has the same hash, and attackers can use huge precomputed tables (rainbow tables) to look hashes up instantly.\nWith salts, every hash is unique, so each password must be attacked separately.","r":"Salt = random per-user value so equal passwords get different hashes.","g":["salt","password_hashing","hashing","n_sha","encryption","credential_stuffing","brute_force"],"fa":"Make identical passwords hash differently, defeating precomputed rainbow tables","cat":"sec"},{"id":"SEC-06","t":"m","l":2,"q":"TLS (HTTPS) provides which guarantees?","o":["Only the encryption of data while it is in transit","Confidentiality, integrity and server identity checks","Protection against XSS attacks in every page served","Login authentication for every visitor by default"],"a":1,"e":"TLS gives three guarantees for data traveling over the network:\n- Confidentiality: it is encrypted, so others cannot read it.\n- Integrity: it cannot be modified without detection.\n- Authentication: the certificate proves you reached the real server.\nIt does NOT protect against bugs in your app (XSS, SQL injection) or prove who the user is.","r":"TLS = private, untampered, real server.","g":["tls","certificate","https","authn","sql_injection","xss"],"fa":"Confidentiality, integrity and server authentication (via certificates)","cat":"sec"},{"id":"SEC-07","t":"m","l":2,"q":"Symmetric vs asymmetric cryptography?","o":["Symmetric uses a public and private key pair","Symmetric: one shared key; asymmetric: a key pair","Asymmetric is always faster than symmetric ciphers","They are the same thing, with different names"],"a":1,"e":"Symmetric: the same secret key locks and unlocks (AES). Very fast, but both sides must somehow share the key safely.\nAsymmetric: each party has a public key (shared with anyone) and a private key (kept secret). Data encrypted with the public key can only be decrypted with the private key; signing with the private key can be verified with the public key. Slower.\nTLS combines them: asymmetric to agree on a key, symmetric for the actual data.","r":"Symmetric = one shared key. Asymmetric = public + private key.","g":["symmetric","asymmetric","encryption","n_aes","tls"],"fa":"Symmetric uses one shared key (fast, e.g. AES); asymmetric uses public/private key pairs (key exchange, signatures, e.g. RSA, ECDSA)","cat":"sec"},{"id":"SEC-08","t":"m","l":1,"q":"Hashing vs encryption?","o":["Both are reversible when you hold the right key","Hashing is one-way; encryption can be reversed","Encryption is one-way; hashing can be reversed","Hashing always requires a secret key to work"],"a":1,"e":"Hashing turns data into a fixed-size fingerprint. You cannot get the original back from it. Used to store passwords and check that files are unchanged.\nEncryption scrambles data so that only someone with the key can turn it back into the original. Used to keep data secret.\nBase64 is neither: it is just a different way of writing the same data, reversible by anyone.","r":"Hash = one-way fingerprint. Encryption = locked box with a key.","g":["hashing","encryption","encoding","hash","secret"],"fa":"Hashing is one-way (integrity, passwords); encryption is reversible with a key (confidentiality)","cat":"sec"},{"id":"SEC-09","t":"m","l":2,"q":"In both the 2021 and 2025 OWASP Top 10, which category is ranked #1?","o":["Injection","Broken Access Control","Cryptographic Failures","Security Misconfiguration"],"a":1,"e":"The OWASP Top 10 is the best-known list of the most critical web application security risks.\nBroken Access Control (users doing or seeing things they should not be allowed to) is #1: it is very common and often severe.\nDefense: check permissions on the server for every request and every object, and deny by default.","r":"#1 web risk: broken access control.","g":["owasp","access_control","authz","sql_injection","xss","z_vulnerability","ssrf"],"cat":"sec"},{"id":"SEC-10","t":"m","l":2,"q":"Changing `/api/orders/1001` to `/api/orders/1002` shows another customer's order. This vulnerability is…","o":["XSS: a malicious script injected into the page","IDOR: broken access control on a direct object ID","Clickjacking: a hidden frame over the real page","CSRF: a forged request sent from another site"],"a":1,"e":"The server checks that you are logged in, but not that order 1002 belongs to YOU. Anyone can change the number and read others' data.\nThat is IDOR, a kind of broken access control.\nFix: on every request, check that the logged-in user owns (or may access) that object, e.g. `WHERE id = :id AND customer_id = :current_user`. Random IDs (UUIDs) make guessing harder but are not a fix on their own.","r":"Always check the user owns the object they request.","g":["idor","access_control","authz","n_uuid","n_sql_clauses"],"fa":"IDOR (Insecure Direct Object Reference), a form of broken access control","cat":"sec"},{"id":"SEC-11","t":"m","l":3,"q":"Your 'fetch image from URL' feature lets an attacker request `http://169.254.169.254/latest/meta-data/`. This is…","o":["SSRF: Server-Side Request Forgery","XSS: cross-site scripting","An open redirect and nothing else","Session fixation of the user's session"],"a":0,"e":"Your server downloads any URL the user gives. The attacker gives an INTERNAL address that only your server can reach, here the cloud metadata service, which can expose credentials.\nThe server becomes a tool to reach internal systems: SSRF.\nDefenses: allow only expected domains, block private and internal IP ranges (checking after DNS resolution), use IMDSv2 on AWS, and isolate the network.","r":"SSRF = tricking your server into calling internal addresses.","g":["ssrf","dns","n_aws","n_ip"],"fa":"SSRF (Server-Side Request Forgery)","cat":"sec"},{"id":"SEC-12","t":"m","l":1,"q":"The principle of least privilege means…","o":["Every new user is given admin rights by default","Each user or token gets only the permissions it needs","Only a single admin account exists for everything","Passwords must be kept short and easy to type"],"a":1,"e":"Give each person, program or key only the access it really needs. A reporting script gets read-only access to one table, not admin on the whole database.\nIf that account is ever compromised, the damage (the 'blast radius') is small.\nReview permissions regularly and remove what is no longer needed.","r":"Minimum access needed, nothing more.","g":["least_privilege","token","z_database","table"],"fa":"Every user, service and token gets only the minimum permissions needed, for the minimum time","cat":"sec"},{"id":"SEC-13","t":"m","l":1,"q":"You accidentally pushed an API key to a public GitHub repo, then deleted the commit. What must you do?","o":["Nothing, because the commit was already deleted","Revoke and rotate the key now; assume it leaked","Make the whole repository private right away","Rename the variable that holds the key in code"],"a":1,"e":"Bots scan GitHub for secrets within minutes, and deleted commits can still exist in forks, caches and clones. Consider the key stolen.\nFirst revoke it and create a new one (rotate), then check logs for misuse, clean the history, and add a secret scanner (pre-commit hook, GitHub secret scanning).\nKeep secrets in environment variables or a secret manager, never in code.","r":"Leaked secret → revoke and rotate immediately.","g":["secret","env_var","api","git_commit","z_variable"],"fa":"Revoke and rotate the key immediately; assume it is compromised, then clean history and add secret scanning","cat":"sec"},{"id":"SEC-14","t":"m","l":3,"q":"Why must a JWT verifier explicitly specify allowed algorithms?","o":["For performance, so verification runs faster","To block `alg: none` and algorithm confusion attacks","Because tokens expire after a time","Algorithms are optional in JWT, so it is not needed"],"a":1,"e":"A JWT header says which algorithm signed it, but that header comes from the client, so an attacker controls it.\nWith `alg: none`, a weak library may accept a token without any signature. With 'algorithm confusion', the attacker signs with HS256 using your PUBLIC key as the secret, and a careless verifier accepts it.\nAlways pass the expected algorithms: `jwt.decode(token, key, algorithms=[\"RS256\"])`, and check `exp`, `aud` and `iss`.","r":"Pin the allowed JWT algorithms; never trust the token's header.","g":["jwt","hmac","asymmetric","token","session","tls","authn"],"fa":"To block attacks like `alg: none` or algorithm confusion (RS256 vs HS256 using the public key as an HMAC secret)","cat":"sec"},{"id":"SEC-15","t":"m","l":2,"q":"Is CORS a security control that protects your API from attackers?","o":["Yes, it blocks all of the unauthorized clients","No. It only tells browsers which origins may read","Yes, it encrypts the responses sent by the API","Yes, but only for the GET requests of the API"],"a":1,"e":"CORS rules are enforced only by browsers, to protect users from malicious websites reading data on their behalf.\nAn attacker can simply call your API with curl, Python or Postman, where CORS does not exist.\nYour API is protected by authentication, authorization and rate limiting. CORS is still important to configure correctly, so it doesn't weaken browser protections.","r":"CORS protects browser users, not your API.","g":["cors","authn","authz","api","rate_limit"],"fa":"No. It only governs which origins a browser lets read responses; attackers can call your API directly with curl","cat":"sec"},{"id":"SEC-16","t":"m","l":2,"q":"Attackers try leaked email/password pairs from other breaches against your login. Strongest mitigation?","o":["Longer session timeouts for every logged-in user","MFA, plus rate limiting and breached-password checks","Hiding the URL of the login page from the public","Switching the login form to use GET requests"],"a":1,"e":"People reuse passwords. When another site is breached, attackers try those email/password pairs on many other sites automatically: credential stuffing.\nMFA stops most of it, because the password alone is not enough.\nAlso rate-limit login attempts per IP and per account, detect bots, and reject passwords known to be in breaches.","r":"Credential stuffing → MFA + rate limiting.","g":["credential_stuffing","mfa","rate_limit","authn","n_ip"],"fa":"Multi-factor authentication, plus rate limiting and breached-password checks","cat":"sec"},{"id":"SEC-17","t":"m","l":3,"q":"Which HTTP header is a strong defense-in-depth layer against XSS?","o":["`Content-Security-Policy`","`Access-Control-Max-Age`","`Cache-Control: max-age`","`Content-Language: en-US`"],"a":0,"e":"A Content-Security-Policy tells the browser which sources of scripts, styles and images are allowed, e.g. only your own domain, and can block inline scripts.\nEven if an attacker manages to inject a `<script>` tag, the browser refuses to run it.\nIt is a second layer ('defense in depth'); escaping output is still the main defense.","r":"CSP = browser allowlist for scripts. Extra layer against XSS.","g":["csp","xss","header","http","s_defense_depth"],"cat":"sec"},{"id":"SEC-18","t":"m","l":3,"q":"What does the `Strict-Transport-Security` (HSTS) header do?","o":["It encrypts the cookies that the site sets","Tells browsers to use only HTTPS for the domain","It blocks the page from being shown in iframes","It enables CORS for requests from other origins"],"a":1,"e":"Even if your site redirects HTTP to HTTPS, the very first request may go over plain HTTP, and an attacker on the network can intercept it and keep the user on HTTP (SSL stripping).\nHSTS tells the browser: 'for the next N months, only ever connect to this domain over HTTPS'. The browser then upgrades every request itself.","r":"HSTS = browser always uses HTTPS for this site.","g":["hsts","https","tls","http"],"fa":"Tells browsers to use HTTPS only for the domain for a period, preventing SSL-stripping downgrades","cat":"sec"},{"id":"SEC-19","t":"m","l":2,"q":"For input validation, which approach is safer?","o":["Denylist: block the known bad characters only","Allowlist: define valid input and reject the rest","No validation is needed when HTTPS is enabled","Validate only on the client side, in the browser"],"a":1,"e":"A denylist tries to block bad things, but attackers always find variations (different encodings, new tricks).\nAn allowlist describes exactly what is acceptable, e.g. 'a positive integer under 1000' or 'one of: small, medium, large', and rejects everything else.\nClient-side validation only improves user experience; the server must always validate (Pydantic does this in FastAPI).","r":"Allowlist what is valid; validate on the server.","g":["input_validation","validation","xss","sql_injection","z_vulnerability","path_traversal"],"fa":"Allowlist: define what valid input looks like (type, length, format) and reject everything else","cat":"sec"},{"id":"SEC-20","t":"m","l":3,"q":"Why is `pickle.loads()` on data from users dangerous?","o":["It is very slow with large objects in memory","Unpickling can run arbitrary code on your server","It silently loses numeric precision of values","It only works on Python 2 and not on Python 3"],"a":1,"e":"Pickle can rebuild any Python object, and it does so by running instructions stored in the data. A malicious pickle can tell Python to run any command on your server.\nThat is remote code execution (RCE), the worst kind of vulnerability.\nFor untrusted data use JSON plus schema validation. Same risk with `yaml.load` without `SafeLoader`.","r":"Never unpickle untrusted data.","g":["pickle","rce","j_deserialization","z_vulnerability","least_privilege","json"],"fa":"Unpickling can execute arbitrary code (remote code execution)","cat":"sec"},{"id":"SEC-21","t":"m","l":2,"q":"A request to `/download?file=../../etc/passwd` returns the system file. This is…","o":["Path traversal","SQL injection","CSRF","Race condition"],"a":0,"e":"`../` means 'go up one folder'. By chaining them, the attacker escapes the downloads folder and reads any file the server can access.\nThat is path traversal.\nFix: never use raw user input as a file path. Map IDs to files on the server, or resolve the final path and check it is still inside the allowed folder.","r":"User input in file paths → path traversal risk.","g":["path_traversal","input_validation","z_vulnerability","least_privilege","access_control"],"cat":"sec"},{"id":"SEC-22","t":"m","l":3,"q":"Session fixation is prevented by…","o":["Using only long session IDs for every user","Regenerating the session ID after every login","Using GET requests for the login endpoint only","Disabling cookies in the browser of the user"],"a":1,"e":"The attacker first gets a valid but anonymous session ID and tricks the victim into using it (e.g. through a crafted link). The victim logs in, and that same session ID now belongs to an authenticated user, which the attacker already knows.\nIf the server issues a NEW session ID at login, the attacker's planted ID becomes useless.","r":"New session ID at every login.","g":["session_fixation","session","cookie","token","authn","https"],"fa":"Regenerating the session ID after login (and privilege changes)","cat":"sec"},{"id":"SEC-23","t":"f","l":3,"q":"Explain at a high level what happens in a TLS handshake.","a":"- Client hello: supported TLS versions and cipher suites, a random value, a key share (TLS 1.3).\n- Server hello: chosen cipher, its key share, and its certificate chain + a signature proving it owns the private key.\n- The client validates the certificate (trusted authority, hostname, not expired).\n- Both sides derive the same symmetric session keys with (EC)DHE key exchange, which gives forward secrecy.\n- Finished messages confirm nothing was tampered with; application data then flows encrypted (AES-GCM or ChaCha20-Poly1305).\n- TLS 1.3 needs one round trip (zero with resumption).","g":["tls","certificate","symmetric","asymmetric","n_aes"],"cat":"sec"},{"id":"SEC-24","t":"f","l":2,"q":"You find a vulnerability in production code. What do you do?","a":"- Assess severity and exploitability (can it be reached? what data is exposed?).\n- Report it through the proper channel (security team or lead) immediately; don't discuss it publicly.\n- Contain: feature flag, WAF rule, rotate exposed secrets.\n- Fix it with tests; look for the same pattern elsewhere in the code.\n- Check logs for signs it was exploited; involve incident response if needed (legal notification duties).\n- Blameless postmortem and preventive controls (linters, SAST, dependency scanning).","g":["feature_flag","postmortem","s_sast_dast","n_waf"],"cat":"sec"},{"id":"SEC-25","t":"m","l":1,"q":"Authentication vs authorization?","o":["They are the same thing under two different names","Authentication proves identity; authorization sets access","Authorization happens before authentication does","Authentication is only needed for admin accounts"],"a":1,"e":"Authentication (authn): the system checks your identity, with a password, token, fingerprint or MFA code.\nAuthorization (authz): knowing who you are, the system checks your permissions: can this user delete this project?\nAuthentication always comes first. In HTTP: 401 = not authenticated, 403 = authenticated but not authorized.","r":"Authn = who you are. Authz = what you can do.","g":["authn","authz","http","mfa","identity"],"fa":"Authentication = proving WHO you are (login); authorization = deciding WHAT you are allowed to do","cat":"sec"},{"id":"SEC-26","t":"m","l":1,"q":"What is multi-factor authentication (MFA)?","o":["Using two different passwords for the same account","Two or more proofs: something you know, have or are","Logging in on two different devices at the same time","Using a much longer and more complex password"],"a":1,"e":"Passwords leak, get guessed or phished. MFA adds another factor of a DIFFERENT type, e.g. a code from an authenticator app or a hardware security key.\nAn attacker with only your password still cannot log in.\nTwo passwords are not MFA: both are 'something you know'.","r":"MFA = password + something you have or are.","g":["mfa","authn","authz","credential_stuffing","brute_force","password_hashing"],"fa":"Requiring two or more different kinds of proof: something you know (password), have (phone, key) or are (fingerprint)","cat":"sec"},{"id":"SEC-27","t":"m","l":1,"q":"An email that looks like it comes from your bank asks you to 'verify your account' on a link. This is typically…","o":["A software update that the bank sends by email","Phishing: tricking people into giving credentials","A CSRF attack that is aimed against the bank","Normal bank procedure for verifying an account"],"a":1,"e":"Phishing uses fake messages that imitate trusted brands to steal passwords, card numbers or MFA codes, usually through look-alike login pages.\nSigns: urgency, slightly wrong sender domains, links to unexpected addresses.\nDefenses: user awareness, MFA (especially phishing-resistant keys), email filtering, and never typing credentials after clicking links in emails.","r":"Phishing = fake messages that steal credentials.","g":["phishing","mfa","xss","credential_stuffing","z_vulnerability","z_malware"],"fa":"Phishing: tricking people into revealing credentials or installing malware","cat":"sec"},{"id":"SEC-28","t":"m","l":1,"q":"Your form checks the email format in JavaScript before sending. Is server-side validation still needed?","o":["No, because the browser has already checked it","Yes: attackers can skip the browser and send requests","Only for the password fields of the same form","Only for requests that come from mobile clients"],"a":1,"e":"Everything on the client can be changed by the user: they can disable JavaScript, edit the page, or send requests with curl or Postman, skipping your checks.\nClient-side validation is for user experience (instant feedback). The server must validate everything again, because only the server is under your control.\nRule: never trust the client.","r":"Never trust the client; always validate on the server.","g":["input_validation","client_server","javascript","validation","z_server"],"fa":"Yes: attackers can skip the browser entirely and send any request directly to the server","cat":"sec"},{"id":"SEC-29","t":"m","l":1,"q":"Which is a property of a cryptographic hash function like SHA-256?","o":["You can easily reverse it to recover the input","Same input, same output; a tiny change alters it all","The output length grows as the input gets longer","It needs a secret key in order to run properly"],"a":1,"e":"A hash function turns any input into a fixed-size fingerprint (SHA-256: 64 hex characters).\n- Deterministic: same input, same hash.\n- One-way: you cannot get the input back from the hash.\n- Tiny change → totally different hash.\n- Collisions (two inputs, same hash) are practically impossible to find.\nUses: checking downloads, digital signatures, git commit IDs. For passwords use a slow, salted variant.","r":"Hash = deterministic, one-way, fixed-size fingerprint.","g":["hashing","n_sha","deterministic","n_git_cmds","hash","v_git"],"fa":"The same input always gives the same output, and a tiny change in input gives a completely different output","cat":"sec"},{"id":"SEC-30","t":"m","l":1,"q":"Where should an application's database password or API keys be kept?","o":["Hardcoded in the source code of the application","In environment variables or a secret manager","In a comment inside the README of the project","In the frontend JavaScript bundle of the site"],"a":1,"e":"Anything in the code ends up in git history, on every developer's laptop and possibly in public. Anything in frontend code is visible to every visitor.\nLoad secrets at runtime from environment variables (`os.environ[\"DB_PASSWORD\"]`) or a secret manager (AWS Secrets Manager, Vault).\nAdd `.env` files to `.gitignore`.","r":"Secrets live outside the code: env vars or a secret manager.","g":["secret","env_var","v_git","api","z_frontend","v_gitignore"],"fa":"In environment variables or a secret manager, never committed to git","cat":"sec"},{"id":"SEC-31","t":"m","l":1,"q":"A library your app uses has a published vulnerability (a CVE). What is the right response?","o":["Ignore it while the app still works as expected","Check if you are affected and update the library","Delete the documentation of the affected library","Rewrite the whole library yourself from scratch"],"a":1,"e":"Most applications are mostly third-party code. A CVE is a public ID for a known vulnerability, and attackers read those lists too.\nCheck if the vulnerable part is used, then upgrade to the fixed version and run your tests.\nAutomate it: tools like Dependabot, `pip-audit` or Snyk flag vulnerable dependencies in every pull request.","r":"Known vulnerable dependency → update; scan dependencies automatically.","g":["cve","dependency","z_vulnerability","v_pull_request","z_library","z_pip"],"fa":"Check whether you are affected and update to a patched version; keep dependencies scanned regularly","cat":"sec"},{"id":"SEC-32","t":"m","l":1,"q":"A website shows the HTTPS padlock. What does that guarantee?","o":["The website is honest and safe to browse and use","The traffic is encrypted and the domain has a cert","The site has no bugs of any kind in its code","Your password is stored safely by the website"],"a":1,"e":"The padlock means TLS is working: nobody in between can read or change the traffic, and the certificate matches the domain name.\nA phishing site like `paypa1-login.com` can also get a valid certificate and a padlock.\nIt also says nothing about how the site stores your data.","r":"Padlock = encrypted connection, not a trustworthy site.","g":["https","tls","certificate","phishing"],"fa":"The connection to that domain is encrypted and the domain owns its certificate; it says nothing about whether the site is trustworthy","cat":"sec"},{"id":"SEC-33","t":"m","l":1,"q":"An attacker tries thousands of passwords per minute on one account. Which control helps most directly?","o":["A bigger server to handle all of the traffic","Rate limiting and account lockout, plus MFA","Changing the URL of the login page every month","Using shorter passwords so users remember them"],"a":1,"e":"Guessing passwords by trying many combinations is a brute-force attack.\nIf the server allows only a few attempts per minute per account and IP (rate limiting), and adds delays or temporary lockouts, guessing becomes impractical.\nMFA makes a correct guess useless on its own.","r":"Brute force → rate limiting + lockout + MFA.","g":["brute_force","rate_limit","mfa","z_brute_force","n_ip"],"fa":"Rate limiting and temporary lockout of login attempts, plus MFA","cat":"sec"},{"id":"SEC-34","t":"m","l":1,"q":"What do SAST, DAST and SCA tools do?","o":["SAST: source code; DAST: running app; SCA: libraries","They are three different types of database engine","They are three modern encryption algorithms for TLS","They only measure the performance of the code"],"a":0,"e":"Security testing happens at different levels:\n- SAST (Static Application Security Testing): analyzes source code or bytecode early, e.g. SonarQube, SpotBugs, Semgrep, CodeQL.\n- DAST (Dynamic): tests a running app like an attacker would, e.g. OWASP ZAP, Burp Suite.\n- SCA (Software Composition Analysis): checks your dependencies against vulnerability databases, e.g. OWASP Dependency-Check, Dependabot, Snyk.\nRunning these in the CI pipeline is part of \"shift left\": find problems early, when they are cheap to fix.","r":"SAST = code, DAST = running app, SCA = libraries.","g":["s_sast_dast","ci","z_vulnerability","j_bytecode","z_database"],"fa":"SAST scans your source code for vulnerabilities without running it; DAST attacks the running application from outside; SCA finds known vulnerabilities in third-party libraries","cat":"sec"},{"id":"SEC-35","t":"m","l":2,"q":"Log4Shell (2021) taught the industry which main lesson?","o":["One dependency flaw can hit thousands: keep an SBOM","Never use Java to build production software","Logging is unsafe and should be disabled entirely","Only the first-party code matters for security"],"a":0,"e":"Log4Shell (CVE-2021-44228) was a critical remote code execution flaw in the Log4j logging library: logging an attacker-controlled string could make the app load and run remote code.\nMany teams did not even know they used Log4j because it came as a transitive dependency.\nLessons: keep a Software Bill of Materials (SBOM), run SCA scans continuously, update dependencies regularly, and never trust input, even when it is just being logged.","r":"Know your dependencies; patch fast; SBOM + SCA.","g":["s_sbom","j_deserialization","v_transitive","s_sast_dast","rce","cve"],"fa":"A vulnerability in a popular transitive dependency can compromise thousands of apps, so you need an inventory of dependencies (SBOM), scanning and fast patching","cat":"sec"},{"id":"SEC-36","t":"m","l":3,"q":"Why is Java deserialization of untrusted data dangerous?","o":["Crafted objects can trigger gadget chains and RCE","It only makes the program run slower overall","It deletes the JVM from the server machine","It only affects Python programs, never Java ones"],"a":0,"e":"Java's native serialization (`ObjectInputStream.readObject`) rebuilds objects from bytes. Special classes run code during that process. An attacker can craft bytes that chain existing classes (a gadget chain) to execute commands.\nMitigations: do not deserialize untrusted data; prefer JSON with strict schemas (Jackson with default typing disabled); use serialization filters (`ObjectInputFilter`); keep libraries updated.\nIt is the Java version of the `pickle.loads` problem.","r":"Never deserialize untrusted Java objects.","g":["j_deserialization","rce","sp_jackson","pickle","json"],"fa":"Reading attacker-controlled serialized objects can trigger malicious code through \"gadget chains\" in classes on the classpath, leading to remote code execution","cat":"sec"},{"id":"SEC-37","t":"m","l":2,"q":"What does \"defense in depth\" mean?","o":["Several independent layers of protection","One very strong firewall at the network edge","Hiding the source code of the application","Using a very long password for each account"],"a":0,"e":"No single control is perfect. Combine layers: input validation, parameterized queries, authentication, authorization, network segmentation, encryption, monitoring, least privilege, and backups.\nExample: even if an attacker finds an XSS hole, a Content-Security-Policy and HttpOnly cookies reduce the damage.","r":"Many layers, so one failure is not fatal.","g":["s_defense_depth","least_privilege","csp","input_validation","httponly","authn"],"fa":"Using several independent layers of protection so that if one fails, others still protect the system","cat":"sec"},{"id":"SEC-38","t":"m","l":2,"q":"What is threat modeling and the STRIDE categories?","o":["Thinking what can go wrong; STRIDE lists six types","A way to model the tables of a database schema","A UI design technique for building the screens","A performance test for the backend of the app"],"a":0,"e":"Threat modeling is done during design: draw the system (data flows, trust boundaries), then ask for each part what could go wrong.\nSTRIDE gives a checklist:\n- Spoofing (pretending to be someone), Tampering (changing data), Repudiation (denying an action), Information disclosure (leaks), Denial of service, Elevation of privilege.\nThen decide mitigations. It is cheaper to fix a design flaw than a deployed system.","r":"STRIDE: Spoofing, Tampering, Repudiation, Info disclosure, DoS, Elevation.","g":["s_threat_model","z_vulnerability","s_defense_depth","least_privilege","access_control","z_trade_off"],"fa":"Thinking systematically about what can go wrong in a design; STRIDE = Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege","cat":"sec"},{"id":"SEC-39","t":"m","l":2,"q":"What is the difference between encryption in transit and encryption at rest?","o":["Transit: data on the network (TLS). Rest: stored data","They are the same thing, only named differently","In transit is for files; at rest is for emails","At rest only applies to passwords stored in the DB"],"a":0,"e":"Data has two main exposure moments:\n- In transit: while traveling between client and server or between services. Use TLS/HTTPS everywhere, including internal service-to-service traffic (sometimes with mutual TLS).\n- At rest: while stored. Use disk, database and backup encryption (AWS KMS, Azure Key Vault keys, TDE in databases).\nManaged cloud storage usually offers at-rest encryption by default; you still must manage keys and access.","r":"Transit = TLS. Rest = encrypted storage with managed keys.","g":["tls","encryption","s_kms","https","n_aws"],"fa":"In transit protects data moving over a network (TLS); at rest protects stored data (disk, database, backups)","cat":"sec"},{"id":"SEC-40","t":"m","l":3,"q":"Which practice best prevents secrets leaking into source code in a Java/Spring project?","o":["Use a secrets manager, scan commits, rotate leaks","Commit them to application.properties in a private repo","Encode them in base64 and keep them in the code","Put them in comments next to the code they unlock"],"a":0,"e":"Private repositories still leak: former employees, forks, build logs, compromised accounts.\nGood practice: secrets live outside the code (Vault, Key Vault, Secrets Manager, Kubernetes Secrets with encryption), loaded at runtime. Use pre-commit/CI secret scanning (gitleaks, GitHub secret scanning). Use workload identities where possible, so there is no secret at all.\nIf one leaks: revoke and rotate immediately; removing the commit does not remove history copies.","r":"Secrets outside code, scanned, rotated, or replaced by workload identity.","g":["secret","env_var","s_kms","n_aws","k8s_secret","encryption"],"fa":"Load them from a secrets manager (Vault, AWS Secrets Manager, Azure Key Vault) or environment variables, scan commits for secrets, and rotate any leaked secret","cat":"sec"},{"id":"SEC-41","t":"m","l":2,"q":"Why is `@Valid` on request bodies plus parameterized queries part of secure coding in Spring?","o":["Validation blocks bad input; bound params stop SQLi","They only improve the speed of each request made","They encrypt all the traffic that the API handles","They hide stack traces from users and bots alike"],"a":0,"e":"Most web vulnerabilities start with untrusted input. Secure coding checklist:\n- Validate input (type, length, format, allow-list) on the server.\n- Use parameterized queries / JPA parameters, never string concatenation.\n- Encode output for the context (HTML, JS) to stop XSS.\n- Check authorization on every request, not only login.\n- Do not leak stack traces or internal errors to clients.\n- Keep dependencies and frameworks patched.","r":"Validate input, parameterize queries, encode output, authorize every call.","g":["input_validation","sql_injection","sp_bean_validation","sql","authz","html"],"fa":"Validation rejects malformed input early, and bound parameters prevent SQL injection; neither alone is enough","cat":"sec"},{"id":"SEC-42","t":"f","l":2,"q":"What software security techniques should a backend developer know?","a":"- Authentication (who are you): password hashing with bcrypt/Argon2, MFA, OAuth2/OIDC, JWT with correct validation.\n- Authorization (what can you do): roles and permissions checked server-side on every request; avoid IDOR.\n- Input validation and output encoding: stops SQL injection, XSS, path traversal.\n- Transport and storage: TLS everywhere, encryption at rest, secrets in a vault.\n- Dependencies: SCA scanning, SBOM, fast patching (Log4Shell lesson).\n- Secure SDLC: threat modeling, code review, SAST/DAST in CI, least privilege, logging and monitoring without sensitive data.\n- Reference: OWASP Top 10 and OWASP ASVS.","g":["password_hashing","input_validation","least_privilege","path_traversal","authn","sql_injection","authz","owasp"],"cat":"sec"},{"id":"SEC-43","t":"m","l":0,"q":"What are the three goals of information security, known as the CIA triad?","o":["Confidentiality, integrity, availability","Compilation, installation, authentication","Cryptography, identity, authorization","Cloud, internet and access management"],"a":0,"e":"- Confidentiality: only authorized people can read the information (NIST: preserving authorized restrictions on information access and disclosure).\n- Integrity: the information cannot be changed in an unauthorized or unnoticed way.\n- Availability: the information and the system are usable when needed.\nExample: encrypting data protects confidentiality, hashes and signatures protect integrity, backups and redundancy protect availability.","r":"CIA = confidentiality, integrity, availability.","g":["z_cia","encryption","hashing","availability","n_nist"],"cat":"sec"},{"id":"SEC-44","t":"m","l":0,"q":"In security, what is a vulnerability?","o":["A weakness that attackers can take advantage of","The name of the attacker who breaks into systems","An antivirus program that scans files for threats","A login screen that asks for user credentials"],"a":0,"e":"Four words that are often mixed up:\n- Vulnerability: a weakness (for example an input that is not validated).\n- Threat: something that could cause harm (a hacker, malware).\n- Exploit: a way to use the weakness.\n- Attack: actually doing it.\nA known vulnerability gets a CVE number, and fixing it is called patching.","r":"Vulnerability = a weakness that can be exploited.","g":["z_vulnerability","cve","owasp","sql_injection","xss","z_patch"],"fa":"A weakness in software, configuration or process that an attacker could use","cat":"sec"},{"id":"SEC-45","t":"m","l":0,"q":"What is malware?","o":["Software made to harm, spy on or steal from users","Software that repairs bugs found in other programs","A hardware component that is built into a computer","A coding style that is used by security teams"],"a":0,"e":"Malware (malicious software) is any program built to do something harmful.\n- Virus/worm: spreads between computers.\n- Ransomware: locks your files and demands payment.\n- Spyware: secretly records what you do.\nIt usually arrives through phishing emails, infected downloads or unpatched vulnerabilities.","r":"Malware = harmful software.","g":["z_malware","phishing","z_firewall","z_patch","z_vulnerability","z_cia"],"fa":"Software designed to harm, spy on or steal from users or systems: viruses, ransomware, spyware","cat":"sec"},{"id":"SEC-46","t":"m","l":0,"q":"What does a firewall do?","o":["It filters network traffic using allow or block rules","It encrypts the whole hard disk of the computer","It makes the internet connection run much faster","It stores the passwords of all the users safely"],"a":0,"e":"A firewall sits between networks (for example the internet and your servers) and decides which connections are allowed, based on rules about address, port and protocol.\nExample rule: allow port 443 (HTTPS) from anywhere, block everything else.\nIn AWS, a security group is described as a virtual firewall for your instances.","r":"Firewall = rules about which connections are allowed.","g":["z_firewall","port","o_security_group","https","n_aws"],"fa":"Filters network traffic with rules, allowing or blocking connections","cat":"sec"},{"id":"SEC-47","t":"m","l":0,"q":"Why should you install software updates and security patches quickly?","o":["They fix known flaws that attackers actively use","They make the display brighter and the text sharper","They only add decorative features to the software","Updates are optional and can be skipped safely"],"a":0,"e":"When a vulnerability is published (with a CVE number), everyone, including attackers, learns about it. Attackers scan for systems that have not updated yet.\nA patch is the update that fixes the problem.\nThis is also why teams scan their dependencies automatically (Dependabot, SCA tools): old libraries are a common way in.","r":"Patch fast: known holes are exploited fast.","g":["z_patch","cve","dependency","z_vulnerability","s_sast_dast"],"fa":"They fix known vulnerabilities that attackers actively try to use","cat":"sec"},{"id":"SEC-48","t":"m","l":0,"q":"What is PII?","o":["Personally Identifiable Information about a person","Public Internet Interface for network connections","Private IP Index, a table of internal addresses","Password Integrity Indicator for strong passwords"],"a":0,"e":"PII needs special care: encrypt it, limit who can see it, keep it out of logs and delete it when it is not needed.\nLaws such as GDPR in Europe set strict rules for personal data.\nA classic mistake is writing emails or tokens into log files.","r":"PII = data that identifies a person. Protect it.","g":["z_pii","least_privilege","encryption","access_control","z_cia","tls"],"fa":"Personally Identifiable Information: data that can identify a person, such as name, ID number, email or address","cat":"sec"},{"id":"SEC-49","t":"m","l":0,"q":"What is OWASP and what is its Top 10?","o":["A non-profit that publishes free security guidance","A cloud provider with a Top 10 of best services","A committee that standardizes programming languages","A government agency that audits large companies"],"a":0,"e":"OWASP (Open Worldwide Application Security Project) produces free articles, tools and cheat sheets about application security.\nThe OWASP Top 10 is its best-known list. In the 2025 edition the first categories are A01 Broken Access Control, A02 Security Misconfiguration, A03 Software Supply Chain Failures, A04 Cryptographic Failures and A05 Injection.\nIt is a good checklist to know for interviews.","r":"OWASP Top 10 = the most critical web security risks.","g":["owasp","access_control","xss","sql_injection","z_vulnerability","s_sast_dast"],"fa":"A non-profit community that publishes free security guidance; the Top 10 lists the most critical risks for web applications","cat":"sec"},{"id":"SEC-50","t":"m","l":0,"q":"Which habit best protects your online accounts?","o":["Using the same short password everywhere to remember it","Long, unique passwords in a password manager, plus MFA","Writing the password into the account name","Sharing it only with friends you trust"],"a":1,"e":"People reuse passwords, so one breached site exposes all the others (credential stuffing).\nA password manager creates and remembers long unique passwords. OWASP's guidance is to allow long passphrases (at least 64 characters).\nMFA adds a second proof, so a stolen password alone is not enough.","r":"Unique long passwords + a manager + MFA.","g":["mfa","credential_stuffing","password_hashing","authn"],"fa":"Using a long, unique password for each account (stored in a password manager) and turning on multi-factor authentication","cat":"sec"},{"id":"FE-01","t":"m","l":1,"q":"What does `0 == \"\"` evaluate to in JavaScript, and `0 === \"\"`?","o":["false, false","true, false","true, true","false, true"],"a":1,"e":"`==` (loose equality) first converts both values to a common type (type coercion). The empty string becomes the number 0, and 0 == 0 is true.\n`===` (strict equality) compares type AND value with no conversion: a number is never equal to a string, so false.\nCoercion rules are full of surprises, so always use `===` and `!==`.","r":"Always use === in JavaScript.","g":["coercion","n_equality","javascript"],"cat":"fe"},{"id":"FE-02","t":"m","l":2,"q":"What is logged?","c":"console.log(a);\nvar a = 1;","o":["1","undefined","ReferenceError","null"],"a":1,"e":"Before running code, JavaScript moves declarations to the top of their scope ('hoisting'). `var a` is hoisted and set to `undefined`; the assignment `= 1` stays where it is.\nSo the code behaves like: `var a; console.log(a); a = 1;` → undefined.\nWith `let` or `const` you would get a ReferenceError: they are hoisted too, but cannot be used before their line (the 'temporal dead zone').","r":"var is hoisted as undefined; let/const throw if used early.","g":["hoisting","var_let_const","scope","closure","function","javascript"],"cat":"fe"},{"id":"FE-03","t":"m","l":2,"q":"What is logged?","c":"for (var i = 0; i < 3; i++) {\n  setTimeout(() => console.log(i), 0);\n}","o":["0 1 2","3 3 3","undefined x3","2 2 2"],"a":1,"e":"`setTimeout` callbacks run later, after the loop has finished.\n`var` creates ONE variable `i` for the whole function, shared by all three callbacks. When they run, `i` is already 3.\nWith `let i`, each loop iteration gets its own new `i`, so it logs 0 1 2.","r":"Loops with callbacks: use let, not var.","g":["var_let_const","closure","callback","event_loop_js","microtask","promise","scope"],"cat":"fe"},{"id":"FE-04","t":"m","l":3,"q":"In what order are the letters logged?","c":"console.log(\"A\");\nsetTimeout(() => console.log(\"B\"), 0);\nPromise.resolve().then(() => console.log(\"C\"));\nconsole.log(\"D\");","o":["A B C D","A D C B","A D B C","A C D B"],"a":1,"e":"JavaScript runs on one thread with an event loop:\n1. First all normal (synchronous) code runs: A, then D.\n2. Then the microtask queue is emptied: promise callbacks → C.\n3. Then the next macrotask runs: timers like setTimeout → B.\nSo promise callbacks always run before timers, even timers set to 0 ms.","r":"Sync code → promise callbacks (microtasks) → timers (macrotasks).","g":["event_loop_js","microtask","promise","callback","event_loop","javascript"],"cat":"fe"},{"id":"FE-05","t":"m","l":2,"q":"How do arrow functions treat `this`?","o":["They bind `this` to the global object always","No own `this`; it comes from the enclosing scope","`this` is always undefined inside every arrow","They treat `this` the same as regular functions"],"a":1,"e":"In a normal `function`, `this` depends on HOW the function is called (e.g. `obj.method()` → obj), which often breaks when you pass it as a callback.\nArrow functions don't have their own `this`; they use the `this` of the code around them. That makes them perfect for callbacks inside methods.\nDon't use arrows for object methods that need `this` to be the object.","r":"Arrow functions borrow this from where they are written.","g":["this_js","arrow_function","function","scope","closure","javascript"],"fa":"They have no own `this`; they capture it lexically from the enclosing scope","cat":"fe"},{"id":"FE-06","t":"m","l":2,"q":"`Promise.all([p1, p2, p3])` when p2 rejects?","o":["It waits for all, then returns results and errors","It rejects when p2 rejects; the others keep running","It ignores p2 and returns the other two results","It retries p2 until it finally succeeds on its own"],"a":1,"e":"`Promise.all` runs promises in parallel and gives you all results, but if ANY of them fails, the combined promise fails immediately with that error. The others are not cancelled; their results are just ignored.\nUse `Promise.allSettled` to get every result and every error, `Promise.race` for the first to finish, `Promise.any` for the first success.","r":"Promise.all fails fast; allSettled waits for everything.","g":["promise","n_promise_all","async_await","callback","event_loop_js","javascript"],"fa":"Rejects as soon as p2 rejects (fail-fast); the other promises keep running","cat":"fe"},{"id":"FE-07","t":"m","l":2,"q":"A list has 1,000 items, each needs a click handler. Best approach?","o":["Attach 1,000 separate listeners, one for each item","Event delegation: one listener on the parent element","Inline `onclick` attributes written on each item","Poll the list every second to check for clicks"],"a":1,"e":"When you click an element, the event 'bubbles' up through all its parents.\nSo you can put ONE listener on the list container and check which item was clicked with `event.target.closest(\"li\")`.\nIt uses less memory and automatically works for items added later.","ec":"list.addEventListener(\"click\", (e) => {\n  const item = e.target.closest(\"li\");\n  if (item) select(item.dataset.id);\n});","r":"Many similar elements → one listener on the parent.","g":["event_delegation","event_bubbling","dom","callback","javascript","debounce"],"fa":"Event delegation: one listener on the parent, use `event.target.closest(...)`","cat":"fe"},{"id":"FE-08","t":"m","l":2,"q":"Search-as-you-type should call the API only after the user pauses typing. Technique?","o":["Throttle","Debounce","Memoization","Polling"],"a":1,"e":"Debounce waits until events STOP for a set time (e.g. 300 ms) and then runs once. Typing 'python' fast triggers one search, not six.\nThrottle runs at most once per interval while events keep coming, good for scroll or resize handlers.\nAlso cancel outdated requests with AbortController so an old, slow response cannot overwrite a newer one.","r":"Debounce = run after the pause. Throttle = run at most every N ms.","g":["debounce","throttle","callback","event_loop_js","promise","javascript"],"cat":"fe"},{"id":"FE-09","t":"m","l":2,"q":"Why does React need a stable `key` on list items?","o":["For the CSS styling of every item in the list","So reconciliation can match items between renders","Keys are optional; they only remove a warning","For SEO indexing of every item in the list"],"a":1,"e":"When a list re-renders, React compares the new items with the old ones to update only what changed. The `key` tells React which old item corresponds to which new one.\nIf you use the array index as key and the list is reordered or filtered, React matches the wrong items: input text or checkbox state can jump to another row.\nUse a stable unique ID from your data.","r":"List keys = stable IDs, not indexes.","g":["reconciliation","react","virtual_dom","component","state","hook"],"fa":"So reconciliation can match items between renders; unstable keys (like array index on reorderable lists) cause wrong state and extra re-mounts","cat":"fe"},{"id":"FE-10","t":"m","l":2,"q":"`useEffect(fn, [])` runs `fn`…","o":["After every render of the same component","Once after mount, and cleans up on unmount","Before the first render of the component","Never, since an empty array disables effects"],"a":1,"e":"`useEffect` runs side effects (fetching data, subscriptions, timers) after React has drawn the component.\nThe dependency array says when to re-run it: `[]` = only after the first render; `[userId]` = whenever userId changes; no array = after every render.\nThe function you return is the cleanup (unsubscribe, clear timers). In development, StrictMode runs effects twice on purpose to reveal missing cleanups.","r":"Dependency array controls when an effect re-runs.","g":["hook","react","component","n_useeffect"],"fa":"Once after the component mounts (cleanup on unmount); in development StrictMode it mounts, unmounts and re-runs once to surface bugs","cat":"fe"},{"id":"FE-11","t":"m","l":2,"q":"Why doesn't this re-render?","c":"const [items, setItems] = useState([]);\nfunction add(x) {\n  items.push(x);\n  setItems(items);\n}","o":["`useState` cannot store arrays, only primitives","The same array reference is set, so React skips it","`push` is asynchronous in plain JavaScript code","`setItems` needs to be awaited before the push"],"a":1,"e":"React decides whether to re-render by checking if the new state is a different object than the old one.\n`push` changes the existing array, so `setItems(items)` passes the SAME array, React sees no change and does nothing.\nAlways create a new array or object: `setItems(prev => [...prev, x])`.","r":"Never mutate React state; create a new copy.","g":["state","immutable","react","n_usestate"],"fa":"The same array reference is passed; React compares with Object.is and skips the update. Create a new array: `setItems([...items, x])`","cat":"fe"},{"id":"FE-12","t":"m","l":3,"q":"What does React's reconciliation do?","o":["It compiles JSX to WebAssembly for the browser","It diffs old and new trees and patches the DOM","It syncs the state of components to the server","It caches the API calls that components make"],"a":1,"e":"Changing the real DOM is slow. When state changes, React builds a new description of the UI, compares it with the previous one ('diffing') and changes only the parts of the real DOM that differ.\nRules: if an element's type changes (div → span), React rebuilds that subtree; in lists, keys identify which child is which.","r":"Reconciliation = diff old and new UI, update only the changes.","g":["reconciliation","virtual_dom","dom","react","state"],"fa":"Diffs the new element tree against the previous one and applies minimal DOM updates","cat":"fe"},{"id":"FE-13","t":"m","l":3,"q":"`useMemo` vs `useCallback`?","o":["They are identical in behavior and purpose","`useMemo` memoizes a value; `useCallback` a function","`useCallback` memoizes values; `useMemo` functions","Both of them cache API responses between renders"],"a":1,"e":"Every render re-runs your component function, recreating values and functions.\n`useMemo(() => expensiveCalc(data), [data])` keeps the RESULT until `data` changes.\n`useCallback(fn, [deps])` keeps the same FUNCTION object, so child components wrapped in `React.memo` don't re-render needlessly.\nUse them where they help, not everywhere.","r":"useMemo → value. useCallback → function.","g":["hook","memoization","react","component","state","props","javascript"],"fa":"`useMemo` memoizes a computed value; `useCallback` memoizes a function reference","cat":"fe"},{"id":"FE-14","t":"m","l":2,"q":"A controlled input in React means…","o":["The DOM holds the value, which is read with a ref","React state is the truth, via `value` and `onChange`","The input is disabled so users cannot type in it","The value is kept in the browser's localStorage"],"a":1,"e":"In a controlled input, React state holds the value: `<input value={name} onChange={e => setName(e.target.value)} />`. Every keystroke updates state, and state decides what is shown.\nThis lets you validate or format as the user types.\nAn uncontrolled input keeps its own value in the DOM and you read it with a ref when needed.","ec":"const [name, setName] = useState(\"\");\n<input value={name} onChange={e => setName(e.target.value)} />","r":"Controlled = React state drives the input.","g":["controlled_input","state","react","dom","n_usestate"],"fa":"React state is the single source of truth via `value` + `onChange`","cat":"fe"},{"id":"FE-15","t":"m","l":2,"q":"With `box-sizing: border-box`, a `width: 200px` element with 20px padding and 2px border renders…","o":["244px wide","200px wide total","220px wide","180px wide"],"a":1,"e":"Every element is a box: content + padding + border (+ margin outside).\nWith the default `content-box`, `width` applies only to the content, so the box is 200 + 2×20 + 2×2 = 244px.\nWith `border-box`, `width` includes padding and border, so the box is exactly 200px. Most projects set `* { box-sizing: border-box }` because it is easier to reason about.","r":"border-box: width includes padding and border.","g":["box_model","css","n_box_sizing","html","selector","specificity"],"cat":"fe"},{"id":"FE-16","t":"m","l":2,"q":"Which CSS selector has the highest specificity?","o":["`div p`","`.card .title`","`#header`","`p`"],"a":2,"e":"When several CSS rules target the same element, the more specific selector wins. Ranking: inline styles > IDs > classes, attributes and pseudo-classes > element names.\n`#header` (one ID) beats `.card .title` (two classes), which beats `div p` (two elements).\nIf specificity is equal, the rule written last wins. Avoid `!important`.","r":"ID > class > element.","g":["specificity","selector","css","html","box_model","flexbox","responsive"],"cat":"fe"},{"id":"FE-17","t":"m","l":1,"q":"Flexbox vs Grid?","o":["Flexbox is two-dimensional; Grid is one-dimensional","Flexbox is one-dimensional; Grid is two-dimensional","They are identical in the layouts they create","Grid only works with table elements in the DOM"],"a":1,"e":"Flexbox arranges items along ONE direction, a row or a column, and is great for toolbars, nav bars and centering things.\nGrid arranges items in rows AND columns at the same time, great for page layouts and card galleries.\nThey are often combined: a Grid page layout with Flexbox inside each card.","r":"Flexbox = one direction. Grid = two directions.","g":["flexbox","grid","css","responsive","box_model","html","media_query"],"fa":"Flexbox lays out in one dimension (row or column); Grid controls rows and columns together","cat":"fe"},{"id":"FE-18","t":"m","l":3,"q":"`<script defer>` vs `<script async>`?","o":["They are identical in how they load and run","`defer` waits for parsing, in order; `async` does not","`async` blocks HTML parsing until it has run","`defer` only works on inline scripts in the page"],"a":1,"e":"A plain `<script>` stops the browser from reading the rest of the HTML until it downloads and runs.\nBoth attributes download in the background:\n- `defer`: runs after the HTML is fully parsed, in the order the scripts appear. Best for your app code.\n- `async`: runs as soon as it arrives, in any order. Fine for independent scripts like analytics.","r":"App scripts → defer. Independent third-party scripts → async.","g":["defer_async","html","javascript","dom","core_web_vitals","http"],"fa":"`defer` runs after HTML parsing in document order; `async` runs as soon as it downloads, order not guaranteed","cat":"fe"},{"id":"FE-19","t":"m","l":3,"q":"Which three metrics are Google's Core Web Vitals today?","o":["TTFB, FCP, TTI","LCP, INP, CLS","FID, LCP, TBT","Speed Index, FCP, CLS"],"a":1,"e":"- LCP (Largest Contentful Paint): how quickly the main content appears. Loading.\n- INP (Interaction to Next Paint): how quickly the page responds to clicks and taps. Responsiveness; it replaced FID in 2024.\n- CLS (Cumulative Layout Shift): how much the layout jumps around while loading. Visual stability.\nThey affect user experience and Google search ranking.","r":"LCP = load, INP = respond, CLS = stability.","g":["core_web_vitals","ssr","hydration","latency","cdn","n_cls"],"cat":"fe"},{"id":"FE-20","t":"m","l":3,"q":"In TypeScript, `unknown` vs `any`?","o":["They are identical in behavior and in safety","`unknown` must be narrowed; `any` turns off checks","`any` is safer than `unknown` when typing data","`unknown` is only used to type caught errors"],"a":1,"e":"`any` switches off type checking: you can do anything with it, and mistakes are only found at runtime.\n`unknown` means 'I don't know the type yet': TypeScript will not let you use it until you check it, e.g. `if (typeof x === \"string\")`.\nUse `unknown` for data from outside (JSON, API responses) and validate it.","r":"Prefer unknown over any.","g":["typescript","type_hint","structural_typing","javascript","generic","json"],"fa":"`unknown` must be narrowed (typeof, instanceof, type guards) before use; `any` disables type checking","cat":"fe"},{"id":"FE-21","t":"m","l":3,"q":"TypeScript's type system is…","o":["Nominal: types match only by their declared name","Structural: types are compatible if shapes match","Dynamic: types are checked at runtime instead","Identical to the type system that Java uses"],"a":1,"e":"TypeScript compares the SHAPE of types, not their names. If an interface requires `{ id: number; name: string }`, any object with those properties fits, even if it was never declared as that interface.\nAlso, types disappear when TypeScript compiles to JavaScript, so data from outside still needs runtime validation.","r":"TypeScript checks shape, not name, and only at compile time.","g":["structural_typing","typescript","duck_typing","javascript"],"fa":"Structural: types are compatible if their shapes match","cat":"fe"},{"id":"FE-22","t":"m","l":2,"q":"Which storage is sent to the server automatically with every matching request?","o":["localStorage","sessionStorage","Cookies","IndexedDB"],"a":2,"e":"Cookies are attached by the browser to every request to their domain, which is why sessions use them. They are small (about 4 KB).\nlocalStorage (permanent) and sessionStorage (per tab) stay in the browser; JavaScript must read them and send them explicitly. Any script on the page can read them, so they are risky for auth tokens.\nIndexedDB is a larger in-browser database.","r":"Only cookies travel automatically with requests.","g":["cookie","web_storage","httponly","origin","https","header","session"],"cat":"fe"},{"id":"FE-23","t":"m","l":3,"q":"What is the main improvement of HTTP/2 over HTTP/1.1?","o":["Headers are always sent in plain text format","Multiplexing many requests over one connection","It removed TLS support from modern browsers","It replaces TCP with a new transport protocol"],"a":1,"e":"HTTP/1.1 handles one request at a time per connection, so browsers opened about 6 connections per site and requests waited in line.\nHTTP/2 sends many requests and responses at the same time over ONE connection (multiplexing) and compresses headers.\nHTTP/3 runs over QUIC (on UDP), which also avoids TCP-level waiting when packets are lost.","r":"HTTP/2 = many requests in parallel on one connection.","g":["http2","http","n_tcp","n_quic","n_udp"],"fa":"Multiplexing many requests over one connection, removing head-of-line blocking at the HTTP layer","cat":"fe"},{"id":"FE-24","t":"m","l":1,"q":"Why prefer `<button>` over a `<div onclick>`?","o":["It is shorter and quicker to type in HTML code","Free keyboard support, focus and screen reader role","A `div` cannot be styled with CSS properties","Buttons load faster than divs in all browsers"],"a":1,"e":"A `<button>` can be reached with Tab, activated with Enter or Space, and is announced as 'button' by screen readers, all automatically.\nA clickable `<div>` does none of that; keyboard and screen-reader users cannot use it unless you add role, tabindex and key handlers yourself.\nUsing the right HTML element for its purpose is called semantic HTML.","r":"Use real buttons, links and labels: accessibility for free.","g":["semantic_html","accessibility","dom","html","javascript","css"],"fa":"Native keyboard support, focus, and correct role for screen readers come for free","cat":"fe"},{"id":"FE-25","t":"m","l":2,"q":"Main advantage of server-side rendering (SSR) over a pure client-side SPA?","o":["No JavaScript at all is needed in the browser","Faster first paint and better SEO (HTML pre-rendered)","It places less load on the server than an SPA","No hydration is needed afterwards on the page"],"a":1,"e":"In a client-side SPA, the browser first receives an almost empty HTML page, downloads JavaScript, runs it, and only then shows content.\nWith SSR, the server sends HTML that already contains the content, so users and search engines see it immediately. Then JavaScript 'hydrates' it to make it interactive.\nCost: more work on the server per request. Static generation (SSG) pre-builds pages at build time.","r":"SSR = content visible sooner + better SEO.","g":["ssr","hydration","html","n_seo","f_spa","javascript"],"fa":"Faster first meaningful paint and better SEO since HTML arrives already rendered","cat":"fe"},{"id":"FE-26","t":"f","l":2,"q":"What happens when you type a URL in the browser and press Enter?","a":"- The browser parses the URL; checks HSTS and its cache.\n- DNS resolution: browser, OS and resolver caches, then recursive lookup → IP address.\n- TCP connection + TLS handshake (or QUIC for HTTP/3).\n- HTTP request with headers and cookies; it may pass a CDN, load balancer, reverse proxy, app server, database/cache.\n- Response: status, headers (caching, cookies), body.\n- Rendering: HTML → DOM, CSS → CSSOM, render tree, layout, paint, composite; scripts may block parsing (unless defer/async); images and other resources are fetched.\n- Mention where you would optimize (CDN, caching, compression, fewer round trips).","g":["dns","tls","cdn","dom","http","load_balancer","reverse_proxy","n_ip"],"cat":"fe"},{"id":"FE-27","t":"f","l":3,"q":"A web page loads slowly. How do you diagnose and improve it?","a":"- Measure first: Lighthouse, Chrome DevTools (Performance, Network), real-user Core Web Vitals.\n- Network: compression (Brotli), CDN, HTTP caching, fewer/smaller requests, preconnect.\n- Assets: optimize images (WebP/AVIF, correct sizes, lazy loading), code splitting, tree shaking, defer non-critical JS.\n- Rendering: avoid huge DOMs and layout thrashing; reserve space for images to prevent CLS; virtualize long lists.\n- Backend: slow time-to-first-byte → profile the API and database, add caching.\n- Set performance budgets and monitor them in CI.","g":["core_web_vitals","cdn","cache","sp_lazy_loading","http","api","n_cls","javascript"],"cat":"fe"},{"id":"FE-28","t":"m","l":1,"q":"In a web page, what are the roles of HTML, CSS and JavaScript?","o":["All three of them do exactly the same job","HTML: structure. CSS: look and layout. JS: behavior","HTML is styling; CSS is logic; JS is content","Only JavaScript is needed to build a web page"],"a":1,"e":"Think of a house:\n- HTML is the structure: walls, rooms, doors. Headings, paragraphs, buttons, forms.\n- CSS is the decoration: paint, furniture placement. Colors, fonts, spacing, layout.\n- JavaScript is the electricity: things that react. Clicks, fetching data, updating the page without reloading.","r":"HTML = what, CSS = how it looks, JS = what it does.","g":["html","css","javascript","react"],"fa":"HTML = structure and content; CSS = appearance and layout; JavaScript = behavior and interactivity","cat":"fe"},{"id":"FE-29","t":"m","l":1,"q":"In modern JavaScript, `let` vs `const`?","o":["They are identical in every way in JavaScript","`const` cannot be reassigned; `let` can be","`const` objects cannot be modified in any way","`let` creates a global variable in all cases"],"a":1,"e":"`const total = 5;` means the variable `total` cannot point to another value later. `let count = 0; count = 1;` is allowed.\nBoth exist only inside the `{ }` block where they are declared.\nCareful: `const` does not freeze objects. `const user = {}; user.name = \"Ana\";` works; only `user = other` is forbidden.\nRule of thumb: use `const` by default, `let` when you must reassign, and avoid `var`.","r":"const by default, let when it changes, never var.","g":["var_let_const","javascript","z_variable","object"],"fa":"`const` cannot be reassigned; `let` can. Both are block-scoped","cat":"fe"},{"id":"FE-30","t":"m","l":1,"q":"What is the DOM?","o":["A database that stores the content of the page","A tree of objects built from the HTML (editable)","A CSS framework used for building page layouts","A server that sends HTML files to the browser"],"a":1,"e":"The browser reads the HTML text and builds the Document Object Model: a tree where each tag is a node (document → html → body → div → button...).\nJavaScript changes the page by changing this tree, e.g. adding an element or changing its text, and the browser redraws what changed.","r":"DOM = the live tree of the page that JS manipulates.","g":["dom","html","tree","javascript","object"],"fa":"The tree of objects the browser builds from the HTML, which JavaScript can read and change","cat":"fe"},{"id":"FE-31","t":"m","l":1,"q":"What does `document.querySelector(\".btn\")` return?","o":["All of the elements that have the class btn","The first match of `.btn`, or null if none","The one element whose id is btn in the page","A string with the HTML of that one element"],"a":1,"e":"`querySelector` accepts any CSS selector and returns the FIRST matching element, or `null` if nothing matches.\n`querySelectorAll` returns ALL matches as a list.\n`.btn` means class 'btn'; `#btn` would mean id 'btn'.","r":"querySelector = first match. querySelectorAll = all matches.","g":["dom","selector","css","class"],"fa":"The first element matching the CSS selector `.btn`, or null if none","cat":"fe"},{"id":"FE-32","t":"m","l":1,"q":"What does this do?","c":"button.addEventListener(\"click\", () => {\n  console.log(\"clicked\");\n});","o":["It clicks the button immediately on page load","It registers a function that runs on every click","It deletes the button from the page when clicked","It logs a message once, when the page loads"],"a":1,"e":"`addEventListener(eventName, callback)` tells the browser: 'when this event happens on this element, call this function'.\nThe function is a callback: you give it to the browser, and the browser calls it later, once per click.\nOther common events: \"input\", \"submit\", \"keydown\", \"scroll\".","r":"addEventListener = run this function when that happens.","g":["callback","dom","javascript","event_bubbling","arrow_function"],"fa":"Registers a function that runs every time the button is clicked","cat":"fe"},{"id":"FE-33","t":"m","l":1,"q":"What is the result of `[1, 2, 3].map(x => x * 10)`?","o":["undefined","[10, 20, 30]","60","[1, 2, 3]"],"a":1,"e":"`map` calls the function on each element and returns a NEW array with the results; the original is unchanged.\n`forEach` also calls the function on each element, but returns undefined; use it only for side effects like logging.\nRelated: `filter` keeps elements where the function returns true; `reduce` combines everything into one value.","r":"map → new array of results. forEach → nothing returned.","g":["arrow_function","f_array_methods","javascript","higher_order","array"],"cat":"fe"},{"id":"FE-34","t":"m","l":1,"q":"What is a React component?","o":["A CSS file with styles for the pages of the app","A reusable UI piece, usually a function returning JSX","A database table for storing the state of the UI","A server route that returns HTML for the pages"],"a":1,"e":"React apps are built from components, like Lego blocks: `<Header />`, `<ProductCard />`, `<Button />`.\nA component is a function that returns JSX, HTML-like syntax describing what to show. React calls it again whenever its data changes and updates the screen.","ec":"function Greeting({ name }) {\n  return <h1>Hello, {name}!</h1>;\n}\n\n<Greeting name=\"Ana\" />","r":"Component = function that returns UI.","g":["component","react","props","state","n_jsx","html"],"fa":"A reusable piece of UI, usually a function that receives props and returns JSX","cat":"fe"},{"id":"FE-35","t":"m","l":1,"q":"In React, props vs state?","o":["They are the same thing under two different names","Props are inputs from the parent; state is internal","State comes only from the server, never from users","Props can only be strings, never objects or numbers"],"a":1,"e":"Props are like function arguments: the parent passes them, the child reads them but must not change them.\nState is the component's own memory (`useState`). When you update it with the setter, React re-renders the component with the new value.\nIf the child needs to change something, the parent passes a function as a prop (e.g. `onChange`).","r":"Props = given by the parent. State = owned and changeable.","g":["props","state","react","component","n_usestate"],"fa":"Props are inputs passed from the parent (read-only for the child); state is data the component owns and can change, triggering a re-render","cat":"fe"},{"id":"FE-36","t":"m","l":1,"q":"What does this CSS do?","c":"@media (max-width: 600px) {\n  .sidebar { display: none; }\n}","o":["It always hides the sidebar on every screen size","It hides the sidebar on screens up to 600px wide","It makes the sidebar exactly 600px wide on screens","It hides the sidebar only on large desktop screens"],"a":1,"e":"A media query applies its CSS rules only when a condition is true, here: the viewport is at most 600px wide (phones).\nThis is the basis of responsive design: one page that adapts its layout to different screen sizes.\nMany teams write mobile styles first and add `min-width` queries for larger screens.","r":"Media queries = CSS that depends on screen size.","g":["media_query","responsive","css","selector","html","box_model"],"fa":"Hides the sidebar only when the screen is 600px wide or narrower","cat":"fe"},{"id":"FE-37","t":"m","l":1,"q":"In CSS, what is the difference between `.btn` and `#btn`?","o":["There is no difference between the two selectors","`.btn` targets a class (many); `#btn` an id (one)","`#btn` targets only the button elements of a page","`.btn` is not a valid selector in modern CSS"],"a":1,"e":"A class (`.`) is a reusable label: many elements can share `class=\"btn\"`.\nAn id (`#`) should identify exactly one element per page.\nFor styling, classes are preferred: IDs have very high specificity, which makes them hard to override later.","r":". = class (many), # = id (one).","g":["selector","specificity","css","class"],"fa":"`.btn` targets elements with class=\"btn\" (can be many); `#btn` targets the element with id=\"btn\" (should be unique)","cat":"fe"},{"id":"FE-38","t":"m","l":1,"q":"What is a Promise in JavaScript?","o":["A guaranteed value that is available right away","An object for a value that arrives later, or an error","A special type of loop that is used for async code","A CSS animation that waits for events on the page"],"a":1,"e":"Operations like `fetch(url)` take time. Instead of freezing the page, they immediately return a Promise: a placeholder for the future result.\nA promise is pending, then becomes fulfilled (with a value) or rejected (with an error).\nYou handle it with `.then(...)` / `.catch(...)` or, more readably, with `await` inside an async function.","r":"Promise = placeholder for a future result.","g":["promise","javascript","n_fetch","object"],"fa":"An object representing a value that will be available later (or an error), from an async operation like a network request","cat":"fe"},{"id":"FE-39","t":"m","l":1,"q":"What does `await` do inside an `async function`?","c":"async function loadUser() {\n  const res = await fetch(\"/api/user\");\n  const user = await res.json();\n  return user;\n}","o":["It blocks the whole browser until the request ends","It pauses this function until the promise settles","It turns the request into a synchronous request","It retries the request until it finally works"],"a":1,"e":"`await` waits for a promise and gives you its value, so async code reads top to bottom like normal code.\nOnly THIS function pauses; the browser keeps handling clicks, animations and other code meanwhile.\nIf the promise rejects, `await` throws, so wrap it in try/catch to handle errors. Note: an async function itself always returns a promise.","r":"await = pause this function, not the page.","g":["promise","async_await","callback","event_loop_js","javascript","n_fetch"],"fa":"Pauses this function until the promise settles, without freezing the rest of the page","cat":"fe"},{"id":"FE-40","t":"m","l":1,"q":"How do you request data from an API in modern JavaScript?","c":"async function loadUser(id) {\n  const res = await fetch(\"/api/users/\" + id);\n  if (!res.ok) throw new Error(\"HTTP \" + res.status);\n  return await res.json();\n}","o":["`fetch` gives a Promise; `await` it and check `res.ok`","`fetch` throws an error on every HTTP error status","`res.json()` gives the data right away, no `await`","`fetch` can only be used to load HTML documents"],"a":0,"e":"`fetch(url)` sends an HTTP request and returns a Promise for a Response object.\nImportant detail: it only rejects on network failure. A 404 or 500 still resolves, so you must check `res.ok` (or `res.status`).\n`res.json()` is also asynchronous, it reads and parses the body, so it needs `await`.\nTo send data: `fetch(url, { method: \"POST\", headers: {\"Content-Type\": \"application/json\"}, body: JSON.stringify(data) })`.","r":"fetch does not reject on HTTP errors: check res.ok.","g":["promise","async_await","json","http","javascript","n_fetch"],"fa":"`fetch` returns a Promise; `await` waits for it; `res.json()` parses the body; you must check `res.ok` because fetch does not reject on 404/500","cat":"fe"},{"id":"FE-41","t":"m","l":1,"q":"What do `package.json` and `npm` do?","o":["`package.json` lists dependencies; `npm` installs them","`npm` is a database in which packages are stored","`package.json` compiles Java code for the backend","`node_modules` is a Git branch with the packages"],"a":0,"e":"Node.js projects (React, build tools) use npm (Node Package Manager), like Maven for JavaScript.\n`package.json`: name, version, `dependencies` (needed to run), `devDependencies` (build/test tools) and `scripts` (`npm run build`, `npm test`).\n`npm install` downloads libraries into `node_modules` (do not commit it) and records exact versions in `package-lock.json`. Alternatives: yarn, pnpm.","r":"package.json = manifest. npm install = download dependencies.","g":["f_npm","metadata","javascript","z_nodejs","react","v_maven"],"fa":"`package.json` lists the project's metadata, scripts and dependencies; `npm` is the tool that installs them into `node_modules`","cat":"fe"},{"id":"FE-42","t":"m","l":2,"q":"What does a bundler such as Vite or webpack do?","o":["It bundles files for the browser, with a dev server","It runs the database that the app depends upon","It replaces the browser that the users install","It writes the tests of the app for the developers"],"a":0,"e":"Browsers cannot run JSX or TypeScript, and loading hundreds of small files is slow.\nA bundler follows imports from your entry file, transpiles the code, minifies it, splits it into chunks and outputs optimized static files.\nDuring development it serves your app and refreshes it instantly when you save (hot module replacement). Vite is the modern default for React; webpack is older; Create React App is deprecated.","r":"Bundler = turns your source into optimized browser files.","g":["f_bundler","typescript","n_jsx","css","javascript","react"],"fa":"It combines and optimizes many JS/CSS/image files (and converts JSX/TypeScript) into a few files the browser can load efficiently, and offers a dev server with hot reload","cat":"fe"},{"id":"FE-43","t":"m","l":1,"q":"In React, how should you update an array stored in state?","c":"const [items, setItems] = useState([\"a\", \"b\"]);\n\nfunction add() {\n  // option A\n  items.push(\"c\");\n  setItems(items);\n\n  // option B\n  setItems([...items, \"c\"]);\n}","o":["Option B: make a new array, so React sees a change","Option A: mutate the array and set the same one","Both options work in exactly the same way in React","Neither option works in React for arrays in state"],"a":0,"e":"React decides to re-render by comparing the old and new state with `===`. If you mutate the same array (`push`) and pass it back, the reference is identical, so React may skip the update.\nAlways create a new value: `[...items, x]`, `items.filter(...)`, `items.map(...)`; for objects `{ ...user, name: \"Ana\" }`.\nTreat state as immutable.","r":"State is immutable: copy, don't mutate.","g":["state","immutable","react","array","n_usestate","n_equality"],"fa":"Option B: create a new array; React detects a new reference and re-renders","cat":"fe"},{"id":"FE-44","t":"m","l":2,"q":"When do you use React Context?","o":["To share a value like a theme without prop drilling","To store the data of the application on the server","To style the components of the application with CSS","To run the tests of the components of the app"],"a":0,"e":"Prop drilling means passing a prop through many intermediate components that do not use it, just to reach a deep child.\nContext lets a provider component make a value available to any descendant that calls `useContext`.\nGood for rarely changing, app-wide data (theme, locale, logged-in user). For complex or frequently changing global state, libraries such as Redux Toolkit, Zustand, or server-state tools like TanStack Query are often used.","r":"Context = shared value without prop drilling.","g":["props","f_context","react","global_state"],"fa":"To share values like the current user or theme with many components without passing props through every level (prop drilling)","cat":"fe"},{"id":"FE-45","t":"m","l":2,"q":"What is `useRef` for?","o":["A mutable value or DOM node that does not re-render","To store state that triggers a re-render of the UI","To fetch data from an API when the component loads","To define the CSS styles of a component in React"],"a":0,"e":"`useRef(initial)` returns an object `{ current: ... }` that React keeps between renders. Changing `current` does NOT re-render.\nUses: focusing an input (`inputRef.current.focus()`), storing a timer id, remembering the previous value, any mutable value that is not part of what the screen shows.\nIf the screen must update when the value changes, use `useState` instead.","r":"useRef = persistent box, no re-render on change.","g":["hook","react","n_useref","mutable","dom","n_usestate"],"fa":"Holding a mutable value or a reference to a DOM element that persists across renders without causing a re-render when it changes","cat":"fe"},{"id":"FE-46","t":"m","l":2,"q":"What is a Single Page Application (SPA) and how does client-side routing work?","o":["One HTML page; JS swaps the view and URL, no reload","A site that is made of one single file on a server","A page that is built without using any JavaScript","A page that reloads completely on every single click"],"a":0,"e":"In a traditional multi-page site, each link asks the server for a new HTML page. In an SPA (React with React Router, Angular, Vue), the first load brings the app; afterwards the router changes the URL with the History API and renders another component, with no full reload. Data comes from REST/JSON APIs.\nBenefits: fast, app-like feel. Drawbacks: larger first load, SEO and initial-render concerns (solved by SSR or static generation, e.g. Next.js).\nThe server must send `index.html` for unknown paths so deep links work.","r":"SPA = one page, JS swaps views, data from APIs.","g":["f_spa","ssr","d_view","html","api","javascript"],"fa":"The browser loads one HTML page and JavaScript; navigation changes the view and URL (History API) without a full page reload, fetching data from APIs as needed","cat":"fe"},{"id":"FE-47","t":"m","l":2,"q":"What does this print?","c":"const nums = [1, 2, 3, 4];\nconst result = nums\n  .filter(n => n % 2 === 0)\n  .map(n => n * 10)\n  .reduce((sum, n) => sum + n, 0);\nconsole.log(result);","o":["60","100","20","[20, 40]"],"a":0,"e":"The chain runs step by step:\n- `filter(n => n % 2 === 0)` keeps even numbers: [2, 4].\n- `map(n => n * 10)` multiplies each: [20, 40].\n- `reduce((sum, n) => sum + n, 0)` adds them starting from 0: 20 + 40 = 60.\nThese three array methods (filter, map, reduce) never change the original array; they return new values.","r":"filter keeps, map transforms, reduce combines.","g":["f_array_methods","arrow_function","higher_order","javascript","n_equality"],"cat":"fe"},{"id":"FE-48","t":"m","l":3,"q":"What is a closure in JavaScript, and what does this log?","c":"function counter() {\n  let n = 0;\n  return () => ++n;\n}\nconst c = counter();\nc(); c();\nconsole.log(c());","o":["3: the inner function remembers its outer `n`","0: each call starts again from zero every time","undefined: `n` is not visible outside of it","1: only the first call changes the value of n"],"a":0,"e":"A closure is a function that keeps access to the variables of the scope where it was created, even after that outer function finished.\n`counter()` returns an arrow function that still sees its own private `n`. Each call increments the same variable: 1, 2, then 3. No outside code can touch `n` directly (data privacy).\nClosures power callbacks, event handlers and React hooks.","r":"Closure = function + remembered variables.","g":["closure","scope","javascript","arrow_function","hook","callback"],"fa":"3: the inner function remembers `n` from where it was created","cat":"fe"},{"id":"FE-49","t":"m","l":2,"q":"What is the difference between Angular, React and Vue at a high level?","o":["React is a library; Angular is a full framework","They are all databases used to store web data","They are all CSS libraries for styling web pages","React is a backend language used to build servers"],"a":0,"e":"All three build interactive UIs from components.\n- React (Meta): library; JSX; large ecosystem; flexible, so teams pick router, state and build tools.\n- Angular (Google): full framework in TypeScript with opinions: modules/standalone components, dependency injection, router, HTTP client, forms.\n- Vue: approachable, template-based; the core is small, official router and store.\nFor an interview, know components, props, state, hooks and how to call a REST API.","r":"React = library. Angular = full framework. Vue = middle.","g":["react","f_spa","typescript","dependency_injection","state","props"],"fa":"React is a UI library focused on components (you choose routing and state tools); Angular is a full framework (TypeScript, DI, router, forms built in); Vue is a progressive framework in between","cat":"fe"},{"id":"FE-50","t":"m","l":2,"q":"Name a common way to test React components.","o":["Jest or Vitest with React Testing Library","Only manual testing carried out in the browser","Maven Surefire, run from the backend project","Selenium only, used for every kind of test"],"a":0,"e":"Jest or Vitest runs tests and provides assertions and mocks. React Testing Library renders components and lets you find elements like a user would (`getByRole`, `getByText`) and trigger events (`userEvent.click`).\nPrinciple: test what the user sees and does, not internal state or implementation details.\nEnd-to-end tests in a real browser use Selenium, Playwright or Cypress.","r":"Jest/Vitest + React Testing Library for components; Playwright/Selenium for E2E.","g":["unit_test","f_rtl","react","e2e_test"],"fa":"Jest (or Vitest) with React Testing Library, which tests behavior the way a user sees it","cat":"fe"},{"id":"FE-51","t":"f","l":2,"q":"How would you connect a React front end to a Spring Boot REST API?","a":"- Spring side: `@RestController` returning JSON; configure CORS for the front-end origin (or serve both from the same origin); secure with Spring Security (JWT or session cookies).\n- React side: call endpoints with `fetch` or axios inside `useEffect` or a data library (TanStack Query) and keep results in state.\n- Handle three states: loading, error, success; check `res.ok`.\n- Auth: send the token in the `Authorization` header or use `HttpOnly` cookies.\n- Dev: Vite dev server proxy to `localhost:8080`; Prod: build static files and serve behind the same domain or a CDN.\n- Contract: agree on DTOs and error format; consider OpenAPI (springdoc) to generate typed clients.","g":["react","sp_rest_controller","sp_security","authz","sp_spring_boot","n_useeffect","n_fetch","rest"],"cat":"fe"},{"id":"FE-52","t":"m","l":0,"q":"What is the frontend of a web application?","o":["The part that runs on a server and stores data","The part users see and use in a browser or app","The marketing team of the company that builds it","The database that stores the application data"],"a":1,"e":"A web application has two sides.\nThe frontend (also called the client side) is everything that runs on the user's device: layout, colors, buttons, forms, and the code that reacts when you click.\nThe backend is the other side. It runs on a server that you never see directly.\nA frontend developer builds what people see and touch.","r":"Frontend = what the user sees and touches.","g":["z_frontend","z_backend","z_client_side","react","z_server"],"fa":"The part users see and interact with in their browser or phone: pages, buttons, forms","cat":"fe"},{"id":"FE-53","t":"m","l":0,"q":"What is a web browser?","o":["A search engine such as Google or Bing online","A program like Chrome that requests and shows pages","A type of server that hosts websites for others","A programming language that is used for the web"],"a":1,"e":"A browser is an app on your device. When you type an address, it sends a request to a server, gets back HTML, CSS and JavaScript, and draws the page for you.\nIn client/server words, the browser is the client.\nA search engine (Google, Bing) is just a website that you open with a browser.","r":"Browser = the app that fetches and shows web pages.","g":["z_browser","client_server","z_server","javascript","html","css"],"fa":"A program (Chrome, Firefox, Safari, Edge) that requests web pages from servers and displays them","cat":"fe"},{"id":"FE-54","t":"m","l":0,"q":"Which sentence correctly describes HTML?","o":["A programming language that does calculations on the server","A markup language for the structure and content of a page","A database format for web data","A language for colors and fonts"],"a":1,"e":"HTML (HyperText Markup Language) uses tags such as `<h1>` (heading) or `<p>` (paragraph) to tell the browser what each piece of content is.\nIt describes structure and content. Looks are CSS and behavior is JavaScript.\nExample: `<p>Hello</p>` is a paragraph element that contains the text Hello.","r":"HTML = structure and content of the page.","g":["html","z_markup","javascript","css"],"fa":"A markup language that defines the structure and content of a web page: headings, paragraphs, links, images","cat":"fe"},{"id":"FE-55","t":"m","l":0,"q":"What does CSS control in a web page?","o":["The look: colors, fonts, spacing and layout","The connection to the database of the website","Which server answers the request of the browser","The login system of the site and its users"],"a":0,"e":"CSS (Cascading Style Sheets) is a language of style rules applied to HTML.\nExample: `p { color: blue; font-size: 18px; }` makes every paragraph blue and bigger.\nWithout CSS, a page still works but looks plain. With a different CSS file, the same HTML can look completely different.","r":"CSS = how the page looks.","g":["css","z_markup","box_model","flexbox","grid","responsive","selector"],"fa":"The presentation: colors, fonts, spacing and layout","cat":"fe"},{"id":"FE-56","t":"m","l":0,"q":"JavaScript and Java: how are they related?","o":["JavaScript is a lighter, simplified version of Java","Different languages; the similar name is historical","They are the same language with two different names","JavaScript can only run inside of Java programs"],"a":1,"e":"Despite the name, they are not related.\nJavaScript was created to add behavior to web pages in the browser. Today it also runs on servers (with Node.js).\nJava is a general-purpose language that is very common in backend and enterprise systems.\nIn an interview, mixing them up is a red flag, so keep them separate in your head: Java is not JavaScript.","r":"Java and JavaScript are different languages.","g":["javascript","z_java","z_programming_language","z_backend","z_nodejs"],"fa":"They are two different programming languages with different purposes; the similar name is historical and causes confusion","cat":"fe"},{"id":"FE-57","t":"m","l":0,"q":"What is the difference between a static and a dynamic website?","o":["Static sites have no images, while dynamic ones do","Static serves fixed files; dynamic builds per request","Static sites need a database; dynamic sites do not","There is no real difference between the two kinds"],"a":1,"e":"Static site: the server just finds a file (for example `about.html`) and sends it as it is. Everyone sees the same content.\nDynamic site: the server runs code, reads data (for example from a database), fills an HTML template and sends a page built for that request. A shop showing your orders is dynamic.\nStatic sites are simpler and cheaper. Dynamic sites are more flexible.","r":"Static = same files for all. Dynamic = built per request.","g":["z_static_dynamic","z_backend","z_database","z_server","html"],"fa":"A static site sends the same ready-made files to every visitor; a dynamic site builds each page on request, often with data from a database","cat":"fe"},{"id":"FE-58","t":"m","l":0,"q":"Where does client-side code run, and where does server-side code run?","o":["Both run on the server, never in the browser","Client-side runs in the browser; server-side on a server","Client-side runs in the DB; server-side in the browser","Both run in the billing system of a cloud provider"],"a":1,"e":"Client-side code is downloaded to the user's device and runs there: for example the JavaScript that opens a menu when you click.\nServer-side code runs on a server you control. It receives requests, talks to the database, checks permissions, and builds the response.\nAnything on the client can be seen and changed by the user, so important checks (security, prices) must be repeated on the server.","r":"Client-side = in the user's browser. Server-side = on your server.","g":["z_client_side","z_backend","z_frontend","z_server","javascript"],"fa":"Client-side runs in the user's browser or app; server-side runs on a server, which receives requests and sends responses","cat":"fe"},{"id":"FE-59","t":"m","l":0,"q":"What is Node.js?","o":["A database used for storing web application data","A JavaScript runtime to run code outside the browser","A CSS framework used for building page layouts","A cloud provider that rents out servers by the hour"],"a":1,"e":"JavaScript was born inside browsers. Node.js is a program that can run JavaScript code on any computer, so you can write a backend or a script in JavaScript.\nNode.js describes itself as a free, open-source, cross-platform JavaScript runtime environment, built to be asynchronous and event-driven.\nA runtime is the program that executes your code.","r":"Node.js = JavaScript outside the browser.","g":["z_nodejs","javascript","z_server","z_backend"],"fa":"A JavaScript runtime that lets you run JavaScript outside the browser, for example to build servers and command-line tools","cat":"fe"},{"id":"FE-60","t":"m","l":0,"q":"What is React?","o":["A database that is used for web applications","A JavaScript library to build UIs from components","An operating system that runs on web servers","A testing tool that is used for Java projects"],"a":1,"e":"React's own website calls it 'the library for web and native user interfaces'.\nYou build a page from components: pieces of UI with their own logic and appearance. A component can be as small as a button or as large as a whole page.\nReact components are JavaScript functions that return markup written in JSX, a syntax that looks like HTML.","r":"React = components for building UIs.","g":["react","component","javascript","interface","z_library","html"],"fa":"A JavaScript library for building user interfaces from reusable components","cat":"fe"},{"id":"FE-61","t":"m","l":0,"q":"What is TypeScript?","o":["A faster version of Java made for the browser","JavaScript with types, compiled down to plain JS","A CSS preprocessor that adds variables and nesting","A query language used for relational databases"],"a":1,"e":"In JavaScript, a variable can hold anything and mistakes appear only while the program runs.\nTypeScript adds types, for example `let age: number = 30;`. The TypeScript compiler catches mistakes (like using a string where a number is expected) before you run the code.\nThe result is converted to normal JavaScript, which is what browsers and Node.js run.","r":"TypeScript = JavaScript + types.","g":["typescript","z_compiler","javascript","z_annotation","z_nodejs"],"fa":"JavaScript with added type annotations; it is checked before running and then compiled to plain JavaScript","cat":"fe"},{"id":"FE-62","t":"m","l":0,"q":"What is the difference between UI and UX?","o":["They are two names for exactly the same thing","UI is what you see; UX is the whole experience","UI is for mobile apps; UX is for desktop apps","UI is the code of the app; UX is the hardware"],"a":1,"e":"UI is the visible surface: buttons, text, layout.\nUX is how the product feels to use: can people find what they need quickly, do they make mistakes, do they get frustrated?\nA beautiful screen (good UI) can still have poor UX if the steps are confusing.","r":"UI = what it looks like. UX = how it feels to use.","g":["z_ui_ux","accessibility","responsive","semantic_html","component","state"],"fa":"UI (user interface) is what you see and use: screens, buttons, colors. UX (user experience) is the whole experience of using the product: how easy, clear and pleasant it is","cat":"fe"},{"id":"FE-63","t":"f","l":0,"q":"Explain frontend and backend to a non-technical person.","a":"- Use the restaurant picture: the dining room is the frontend (what the customer sees and touches: menu, table, plates).\n- The kitchen is the backend (where the work and the ingredients are, hidden from the customer).\n- The waiter who carries orders between them is the API.\n- Frontend: HTML, CSS, JavaScript running in the browser.\n- Backend: code on a server (Java, Python, Node.js...) plus a database that stores the data.\n- A full-stack developer works on both sides.","g":["z_frontend","z_backend","api","javascript","z_nodejs","html","z_java","css"],"cat":"fe"},{"id":"OPS-01","t":"m","l":1,"q":"What is the key difference between a container and a virtual machine?","o":["Containers boot a full guest OS kernel, so they are as heavy as a VM","Containers share the host kernel; VMs run their own kernel on virtual hardware","VMs start faster than containers because they skip the OS boot step","Containers cannot limit CPU or memory, so a VM is needed for limits"],"a":1,"e":"A virtual machine emulates a whole computer and runs a complete operating system inside it: strong isolation, but heavy (GBs, minutes to boot).\nA container is just an isolated process on the host's Linux kernel, packaged with its app and libraries. It is light (MBs) and starts in seconds.\nThat is why you can run dozens of containers on one laptop. (On Mac/Windows, Docker runs a small Linux VM underneath.)","r":"VM = whole computer. Container = isolated process sharing the kernel.","g":["container","vm","z_linux","n_os","o_docker_cli"],"fa":"Containers share the host kernel and isolate processes (namespaces, cgroups); VMs virtualize hardware and run their own kernel","cat":"ops"},{"id":"OPS-02","t":"m","l":2,"q":"Which Dockerfile ordering makes rebuilds fastest when only your source code changes?","c":"# Option A\nCOPY . .\nRUN pip install -r requirements.txt\n\n# Option B\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\nCOPY . .","o":["A","B","Both are identical","Neither uses the cache"],"a":1,"e":"Docker builds an image in layers, one per instruction, and reuses (caches) a layer if nothing it depends on changed.\nIn A, editing any source file changes the `COPY . .` layer, so every layer after it, including the slow `pip install`, is rebuilt.\nIn B, dependencies are installed from requirements.txt alone; that layer is reused until requirements change, and only the final copy reruns.","r":"Copy what changes rarely first, what changes often last.","g":["layer_cache","dockerfile","docker_image","o_docker_cli"],"cat":"ops"},{"id":"OPS-03","t":"m","l":2,"q":"Why use a multi-stage Docker build?","o":["To run several containers at once from a single Dockerfile","To compile in one stage and copy only the artifacts into a small image","To build for several CPU architectures automatically in one step","To avoid writing a Dockerfile by reusing the one from another image"],"a":1,"e":"Building often needs heavy tools (compilers, build dependencies, Node to bundle a frontend) that the running app does not need.\nA multi-stage build uses a first 'builder' stage with all tools, then a second, slim stage that copies only the finished result.\nThe final image is smaller, downloads faster and has fewer things an attacker could exploit.","r":"Multi-stage = build big, ship small.","g":["multi_stage","docker_image","o_docker_cli"],"fa":"To build/compile in one stage and copy only the artifacts into a small runtime image","cat":"ops"},{"id":"OPS-04","t":"m","l":2,"q":"`CMD` vs `ENTRYPOINT` in a Dockerfile?","o":["They are identical, and either can be used for any purpose","`ENTRYPOINT` sets the program; `CMD` gives default arguments you can override","`CMD` runs once at build time; `ENTRYPOINT` runs every time at start","`ENTRYPOINT` is deprecated, so only `CMD` should be used today"],"a":1,"e":"Both define what runs when the container starts.\n`ENTRYPOINT` is the fixed program (e.g. gunicorn). `CMD` provides default arguments, which you can replace by adding arguments to `docker run image ...`.\nUse the JSON form `[\"gunicorn\", \"app:app\"]` so your app runs as the main process and receives stop signals properly.","r":"ENTRYPOINT = the program. CMD = its default arguments.","g":["dockerfile","signal","default_arg","o_docker_cli","json"],"fa":"`ENTRYPOINT` sets the executable; `CMD` provides default arguments that are easily overridden at `docker run`","cat":"ops"},{"id":"OPS-05","t":"m","l":1,"q":"Why mount a volume for a PostgreSQL container?","o":["To speed up the queries that the database handles in memory","Container data is lost when the container is removed; a volume keeps it","Volumes are needed so that the container can expose its ports","To share the kernel of the host with the database process"],"a":1,"e":"Containers are meant to be disposable: you delete and recreate them on every update. Anything written inside the container is deleted with it.\nA volume is storage managed outside the container's lifecycle. Mounting it at the database's data folder keeps the data when the container is replaced.","r":"Data that must survive → volume.","g":["volume","container","docker_image","o_pvc","o_docker_cli"],"fa":"Data in the container's writable layer is lost when the container is removed; a volume persists it","cat":"ops"},{"id":"OPS-06","t":"m","l":2,"q":"A container starts and exits immediately with code 0. Most likely cause?","o":["The container ran out of memory and was stopped by the system","Its main process (PID 1) finished, like a script that simply ended","The image is corrupt, so the container cannot keep running","The Docker daemon crashed and stopped every running container"],"a":1,"e":"A container lives exactly as long as its main process. Exit code 0 means that process ended successfully: there was simply nothing left to do.\nCommon causes: the command runs a short script, or starts a server in the background (daemon mode) and then returns.\nRun the server in the foreground as the main process.","r":"Main process ends → container stops.","g":["container","exit_code","o_docker_cli","docker_image","signal","dockerfile"],"fa":"Its main process (PID 1) finished, e.g. the command ran a script and returned","cat":"ops"},{"id":"OPS-07","t":"m","l":3,"q":"A container is killed with exit code 137. What usually happened?","o":["A syntax error in the code stopped the container at startup","It got SIGKILL (128 + 9), often from the OOM killer at the memory limit","A normal shutdown that was requested with `docker stop`","A network timeout while the container pulled its image"],"a":1,"e":"Exit codes above 128 mean 'killed by a signal': code = 128 + signal number. 137 = 128 + 9, and signal 9 is SIGKILL, which cannot be caught.\nThe most common reason is the container using more memory than its limit, so the kernel's OOM (out-of-memory) killer stops it.\nCheck with `docker inspect` (OOMKilled: true) or `kubectl describe pod`. 143 = SIGTERM, a normal stop request.","r":"137 = killed (often out of memory). 143 = asked to stop.","g":["exit_code","oom","signal","o_kubectl","pod"],"fa":"It received SIGKILL (128 + 9), very often from the OOM killer hitting the memory limit","cat":"ops"},{"id":"OPS-08","t":"m","l":1,"q":"What is Docker Compose mainly used for?","o":["Orchestrating production clusters across many separate hosts","Running multi-container apps from one YAML file, mostly in dev","Building images faster by sharing a remote cache between many hosts","Replacing Kubernetes in every production environment of a company"],"a":1,"e":"A real app often needs several containers: your API, PostgreSQL, Redis, a worker. Starting each by hand is tedious.\nWith Compose you describe all of them, plus their ports, volumes and environment variables, in `docker-compose.yml`, and start everything with `docker compose up`.\nFor production across many machines, Kubernetes or a managed container service is more common.","r":"Compose = many containers, one file, one command.","g":["docker_compose","container","o_yaml","ci","z_database","env_var"],"fa":"Defining and running multi-container setups (app, DB, cache) from one YAML file, typically for local dev and CI","cat":"ops"},{"id":"OPS-09","t":"m","l":2,"q":"In Kubernetes, what is a Pod?","o":["A physical server that is joined to the cluster as a worker","The smallest unit: containers that share network and volumes","A load balancer that sends the traffic to the services","A registry where all the container images are stored"],"a":1,"e":"Kubernetes does not run containers directly; it runs Pods. A Pod usually holds one main container, sometimes with helper containers ('sidecars') that share its network and storage.\nPods are disposable: when one dies or is replaced, the new one gets a new IP address. That is why you put a Service in front of them.","r":"Pod = smallest unit Kubernetes runs; disposable.","g":["pod","kubernetes","container","n_ip"],"fa":"The smallest deployable unit: one or more containers sharing network namespace and volumes","cat":"ops"},{"id":"OPS-10","t":"m","l":2,"q":"Which Kubernetes object manages rolling updates and keeps N replicas running?","o":["Pod","Deployment","ConfigMap","Namespace"],"a":1,"e":"A Deployment says 'I want 3 copies of this Pod running, with this image'. Kubernetes keeps that true: if a Pod dies, it creates a new one.\nWhen you change the image version, it replaces Pods gradually (rolling update), so the app stays available, and you can go back with `kubectl rollout undo`.\nFor databases that need stable identities and disks, StatefulSets are used instead.","r":"Deployment = desired number of Pods + rolling updates.","g":["deployment_k8s","pod","rollback","kubernetes","o_statefulset","o_kubectl"],"cat":"ops"},{"id":"OPS-11","t":"m","l":2,"q":"What does a Kubernetes Service provide?","o":["Persistent storage that keeps its data when a pod restarts","A stable IP or DNS name that load-balances across the matching pods","Container image builds triggered from a Git repository","Encryption of the secrets stored in the cluster"],"a":1,"e":"Pods come and go with changing IPs, so other apps cannot rely on them directly.\nA Service gives a stable name (e.g. `http://orders`) and spreads traffic across all healthy Pods that have the matching labels.\nTypes: ClusterIP (internal only), NodePort, LoadBalancer (external). An Ingress routes outside HTTP traffic to Services.","r":"Service = stable address in front of changing Pods.","g":["service_k8s","pod","load_balancer","kubernetes","dns","n_ip"],"fa":"A stable virtual IP/DNS name that load-balances to a changing set of pods selected by labels","cat":"ops"},{"id":"OPS-12","t":"m","l":3,"q":"Readiness probe vs liveness probe?","o":["They are identical, and both restart the container when they fail","Failing readiness removes the pod from traffic; failing liveness restarts it","Liveness controls the traffic; readiness restarts the container","Both checks delete the pod from the cluster when they fail once"],"a":1,"e":"Kubernetes regularly calls health endpoints of your app.\n- Readiness: 'can you handle requests right now?' If not (still starting, warming a cache), the Pod gets no traffic, but is not restarted.\n- Liveness: 'are you still working at all?' If not (stuck, deadlocked), the container is restarted.\nDon't check the database in the liveness probe: a database outage would restart all your Pods at once.","r":"Readiness = send traffic? Liveness = restart?","g":["probe","pod","o_kubectl","deployment_k8s","service_k8s","o_crashloop"],"fa":"Readiness failing removes the pod from Service traffic; liveness failing restarts the container","cat":"ops"},{"id":"OPS-13","t":"m","l":2,"q":"Where should a database password go in Kubernetes?","o":["Inside the container image, so that it is always available","In a ConfigMap, next to the other settings of the app","In a Secret, ideally from an external manager, as env var or file","Hardcoded in the Deployment YAML, which is kept in git"],"a":2,"e":"ConfigMaps are for normal settings; Secrets are for sensitive values, injected into Pods as environment variables or files.\nNote: Kubernetes Secrets are only base64-encoded by default (not encrypted), so enable encryption at rest and restrict who can read them, or sync them from a real secret manager (Vault, AWS Secrets Manager).\nNever put passwords in the image or in YAML committed to git.","r":"Passwords → Secret, not ConfigMap, never in git.","g":["k8s_secret","secret","kubernetes","o_configmap","v_git","env_var"],"fa":"In a Secret (ideally backed by an external secret manager), injected as env var or file","cat":"ops"},{"id":"OPS-14","t":"m","l":2,"q":"Continuous Delivery vs Continuous Deployment?","o":["They are the same thing under two different names","Delivery needs a manual approval to release; Deployment is automatic","Deployment means releasing only to staging, not to production","Delivery skips the automated tests to be faster"],"a":1,"e":"Both start with Continuous Integration: every commit is built and tested automatically.\nContinuous Delivery: every change that passes is ready to go to production, but a human clicks the 'deploy' button.\nContinuous Deployment: no button; if all checks pass, it goes to production automatically. That requires strong tests, monitoring and fast rollback.","r":"Delivery = ready + manual button. Deployment = automatic.","g":["ci","cd","pipeline","rollback"],"fa":"Delivery: every change is releasable and deployed with a manual approval; Deployment: every passing change goes to production automatically","cat":"ops"},{"id":"OPS-15","t":"m","l":2,"q":"Which order makes the most sense for a CI/CD pipeline?","o":["Deploy to prod, then run the tests, then build the image","Lint and unit tests, build, integration tests, staging, smoke tests, prod","Build, deploy to prod, then lint the code afterwards","Deploy to staging only on Fridays, then run all tests at once"],"a":1,"e":"Run the fastest, cheapest checks first so problems are found in seconds (fail fast): linting and unit tests.\nThen build the artifact (Docker image) ONCE, run slower integration tests, deploy to staging and smoke-test it.\nFinally promote that same image to production, so what you tested is exactly what you ship.","r":"Cheap checks first; build once; promote the same artifact.","g":["pipeline","ci","cd","staging","integration_test","unit_test"],"fa":"Lint and unit tests → build image → integration tests → deploy staging → smoke tests → deploy prod","cat":"ops"},{"id":"OPS-16","t":"m","l":2,"q":"What does `terraform plan` do?","o":["It applies the changes immediately to the real infrastructure","It compares config and state and shows what would change","It deletes the state file so that the next run starts from clean","It formats the code files so that they match the Terraform style"],"a":1,"e":"Terraform describes infrastructure (servers, databases, networks) as code. That is Infrastructure as Code.\n`terraform plan` is a dry run: it compares your code with what exists and lists what it WOULD create, change or destroy. Nothing changes yet.\nAfter reviewing, `terraform apply` makes the changes. The state file maps code to real resources; keep it in shared remote storage with locking.","r":"plan = preview. apply = do it.","g":["terraform","iac","immutable_infra","rollback","cloud"],"fa":"Compares desired config with state and real infrastructure, and shows what would change without changing anything","cat":"ops"},{"id":"OPS-17","t":"m","l":2,"q":"According to the Twelve-Factor App, where should configuration that varies between environments live?","o":["In hardcoded constants inside the source code","In environment variables, kept outside the code","In a shared spreadsheet that the whole team edits","Inside the Docker image, baked in at build time"],"a":1,"e":"The same code runs in development, staging and production; only settings differ (database URL, API keys, debug mode).\nKeeping those settings in environment variables means you build the image once and run it anywhere with different config, and secrets never land in the code.\nThe Twelve-Factor App is a well-known checklist for cloud-friendly apps (also: stateless processes, logs to stdout).","r":"Config that changes per environment → environment variables.","g":["twelve_factor","env_var","secret","k8s_secret","o_configmap","api"],"fa":"Environment variables (or injected config), not in the code","cat":"ops"},{"id":"OPS-18","t":"m","l":1,"q":"What is Amazon S3?","o":["A relational database service that is managed by AWS for you","Object storage for files, with high durability, used over HTTP","A container orchestrator that schedules and runs your workloads","A CDN that caches content at locations close to your users"],"a":1,"e":"S3 stores files (called objects) in buckets, almost without size limits and with very high durability (data copied across facilities).\nYou read and write via an HTTP API, not like a normal disk. Typical uses: user uploads, images, backups, static websites, data for analytics.\nCommon trick: give the browser a temporary pre-signed URL so it uploads directly to S3 instead of through your server.","r":"S3 = durable storage for files in the cloud.","g":["s3","object_storage","http","object","api","z_url"],"fa":"Object storage for files/blobs with high durability, accessed over HTTP APIs","cat":"ops"},{"id":"OPS-19","t":"m","l":2,"q":"Which is a known limitation of AWS Lambda?","o":["It cannot run Python, only Java and Node.js code","A 15-minute maximum run time and cold-start latency","It always runs on one fixed server that you must manage","It cannot be triggered by HTTP requests, only by timers"],"a":1,"e":"Lambda is 'serverless': you upload a function, AWS runs it when an event arrives (HTTP call, file uploaded, queue message) and you pay per execution.\nLimits: each run can last at most 15 minutes, and after being idle the first call can be slower while a new environment starts (cold start).\nGreat for spiky, event-driven work; for long jobs or constant heavy traffic, containers are often simpler and cheaper.","r":"Lambda = event-driven functions, max 15 min, cold starts.","g":["serverless","s3","iam","cloud","autoscaling","n_aws"],"fa":"Maximum execution time of 15 minutes and cold-start latency","cat":"ops"},{"id":"OPS-20","t":"m","l":2,"q":"How should an app running on EC2 or ECS access S3?","o":["Hardcode access keys in the code of the application","Use an IAM role on the instance or task, with temporary credentials","Make the bucket public so that no credentials are needed","Email the access keys to the ops team to configure them"],"a":1,"e":"IAM (Identity and Access Management) controls who can do what in AWS.\nInstead of storing permanent keys, you attach a role to the server or container. The AWS SDK automatically gets short-lived credentials from it, rotated for you.\nGive the role only what it needs, e.g. read/write on one bucket (least privilege).","r":"AWS access from your servers → IAM roles, not stored keys.","g":["iam","least_privilege","secret","n_aws","o_ec2","o_ecs_eks"],"fa":"Use an IAM role attached to the instance/task, which provides temporary rotating credentials","cat":"ops"},{"id":"OPS-21","t":"m","l":3,"q":"SQS vs SNS?","o":["They are the same service, sold under two different names","SQS is a queue consumers pull from; SNS pushes to subscribers","SNS stores messages for 14 days so that consumers can poll them","SQS is a service meant for sending email messages to customers"],"a":1,"e":"SQS (Simple Queue Service): messages wait in a queue; workers pull them and each message is handled by one worker. For distributing jobs.\nSNS (Simple Notification Service): publish to a topic and it pushes a copy to every subscriber (queues, Lambdas, emails).\nCommon pattern 'fan-out': SNS topic → one SQS queue per interested service.","r":"SQS = queue (one consumer per message). SNS = broadcast.","g":["sqs_sns","message_queue","pub_sub","worker","delivery_semantics","s3"],"fa":"SQS is a queue consumers pull from (each message processed by one consumer); SNS is pub/sub that pushes each message to all subscribers","cat":"ops"},{"id":"OPS-22","t":"m","l":2,"q":"How do you make a service resilient to a single data center failure on AWS?","o":["Use a bigger instance type so that it does not fail","Run across several Availability Zones behind a load balancer","Take daily snapshots and restore them after a failure","Use a single AZ with an auto-restart policy on the instance"],"a":1,"e":"An AWS region (e.g. eu-west-1) contains several Availability Zones: separate data centers with independent power and networking.\nIf all your servers are in one AZ, a problem there takes you down. Spread instances across 2-3 AZs behind a load balancer and use a database with a standby in another AZ.\nMulti-region protects against a whole region failing, at a higher cost.","r":"Spread across Availability Zones.","g":["availability_zone","high_availability","load_balancer","n_aws"],"fa":"Run instances across multiple Availability Zones behind a load balancer, with a multi-AZ database","cat":"ops"},{"id":"OPS-23","t":"m","l":2,"q":"What do feature flags let you do?","o":["Speed up the builds by skipping the modules that did not change","Separate deployment from release: ship the code off, enable it later","Replace the tests with checks that are run on the live system","Encrypt the traffic that moves between the services of the app"],"a":1,"e":"A feature flag is an if-condition controlled by configuration: `if flags.enabled(\"new_checkout\", user): ...`.\nYou can deploy unfinished code switched off, then enable it for staff, then 10% of users, then everyone. If something goes wrong, switch it off in seconds without a new deploy.\nRemove old flags once a feature is fully released.","r":"Feature flag = deploy now, release when ready, off switch included.","g":["feature_flag","canary","blue_green","rollback","pipeline"],"fa":"Decouple deployment from release: ship code dark, enable it gradually or per user, and turn it off without redeploying","cat":"ops"},{"id":"OPS-24","t":"m","l":2,"q":"On a Linux server, which command shows which process is listening on port 8000?","o":["`ps aux | grep 8000`, which lists processes with that text","`ss -ltnp | grep :8000` (or `lsof -i :8000`)","`chmod 8000`, which changes file permissions","`top -p 8000`, which monitors a process with that PID"],"a":1,"e":"`ss` lists network sockets: `-l` listening, `-t` TCP, `-n` numeric ports, `-p` show the process. `lsof -i :8000` gives similar information.\nUseful when you get 'address already in use' when starting a server.\n`ps aux | grep 8000` only searches process command lines for the text '8000'.","r":"Who uses port X? → ss -ltnp or lsof -i :X.","g":["port","ssh","z_linux","z_terminal","signal","n_tcp"],"cat":"ops"},{"id":"OPS-25","t":"m","l":3,"q":"What is immutable infrastructure?","o":["Servers that can never be rebooted after they start running","Never patching servers in place: build a new image and replace","Databases that are set to read-only mode in production","Infrastructure that is created by hand and never by code"],"a":1,"e":"In the old approach, servers were logged into and updated by hand over the years. Each one ended up slightly different ('configuration drift') and hard to recreate.\nWith immutable infrastructure, you never modify a running server: you build a new image (container or VM image) in CI and replace the old servers with new ones.\nRolling back is just running the previous image.","r":"Don't patch servers; replace them with a new image.","g":["immutable_infra","docker_image","immutable","vm","ci"],"fa":"Never patching servers in place; build a new image/instance for every change and replace the old one","cat":"ops"},{"id":"OPS-26","t":"m","l":3,"q":"What does Kubernetes' Horizontal Pod Autoscaler do?","o":["It adds new nodes to the cluster when the load of the app grows","It changes the number of pod replicas based on CPU or custom metrics","It raises the memory limit of a pod when the pod runs short","It moves pods between regions to balance the load of the cluster"],"a":1,"e":"The HPA watches a metric (e.g. average CPU at 70%) and adds Pods when load rises and removes them when it falls.\nIt changes the NUMBER of Pods (horizontal). Adding more machines to the cluster is the job of the Cluster Autoscaler; changing a Pod's CPU/memory size is the Vertical Pod Autoscaler.\nIt needs resource requests defined to calculate utilization.","r":"HPA = more or fewer Pods based on load.","g":["autoscaling","pod","horizontal_scaling","n_cpu","n_hpa","kubernetes"],"fa":"Changes the number of pod replicas based on metrics like CPU or custom metrics","cat":"ops"},{"id":"OPS-27","t":"m","l":2,"q":"In a blameless postmortem, the focus is on…","o":["Finding out who made the mistake so that they can be warned","The timeline, root causes, contributing factors and action items","Hiding the incident from the customers until it is solved","Rewriting the whole system that failed during the incident"],"a":1,"e":"After an incident, the team writes what happened (timeline), why (root causes and contributing factors), what went well, and what to change.\n'Blameless' because people act on the information they had at the time; blaming makes people hide mistakes.\nThe output is concrete action items: better alerts, safer tooling, tests, runbooks.","r":"Postmortem = learn and fix the system, not blame people.","g":["postmortem","observability","sli_slo_sla","rollback","logs"],"fa":"Timeline, root causes and contributing factors, and concrete action items to prevent recurrence","cat":"ops"},{"id":"OPS-28","t":"f","l":2,"q":"Describe a CI/CD pipeline you would set up for a Python web service.","a":"- On every PR: install with locked dependencies (cached), format/lint (ruff), type check (mypy), unit tests with coverage (pytest), dependency and secret scanning.\n- On merge to main: build one Docker image tagged with the commit SHA, push to a registry.\n- Integration tests against real dependencies (database in containers).\n- Deploy to staging automatically (backward-compatible DB migrations first), run smoke tests.\n- Deploy to production with approval or automatically, rolling/canary, health checks.\n- Monitor error rate and latency; automatic rollback if they spike.\n- Tools: GitHub Actions/GitLab CI, Terraform for infrastructure, secrets from a manager.","g":["ci","cd","pipeline","docker_image","integration_test","smoke_test","terraform","unit_test"],"cat":"ops"},{"id":"OPS-29","t":"f","l":2,"q":"Production breaks right after a deploy. What do you do?","a":"- Acknowledge and communicate: open an incident channel, assign roles, post status updates.\n- Mitigate first, diagnose later: roll back the deploy or switch off the feature flag.\n- Confirm recovery with metrics (errors, latency).\n- Investigate with logs, traces and the diff of the deploy.\n- Fix forward with a test that reproduces the bug.\n- Blameless postmortem: timeline, root cause, why tests or the canary did not catch it, action items.","g":["rollback","feature_flag","postmortem","logs","observability","ci","z_deploy"],"cat":"ops"},{"id":"OPS-30","t":"m","l":1,"q":"Docker image vs container?","o":["They are the same thing, a different word for one concept","An image is a read-only template; a container is a running instance","A container is a file you download; an image is what runs","Images run only on Linux servers, while containers run anywhere"],"a":1,"e":"Think of a class and its objects: the image is the blueprint, the container is the running thing.\nYou build an image once (`docker build`), push it to a registry, and start as many containers from it as you need (`docker run`).\nEach container gets its own isolated filesystem changes, which disappear when it is removed.","r":"Image = template. Container = running instance.","g":["docker_image","container","instance","o_docker_cli","object"],"fa":"An image is a read-only template (app + dependencies); a container is a running instance created from an image","cat":"ops"},{"id":"OPS-31","t":"m","l":1,"q":"What is a Dockerfile?","o":["A log file that records the steps of a build","A text file with step-by-step instructions to build an image","A configuration file for the Docker settings of the computer","A list of the containers that are currently running"],"a":1,"e":"A Dockerfile is a recipe: start from a base image, copy files, install dependencies, define the start command. `docker build` runs it and produces an image.","ec":"FROM python:3.12-slim\nWORKDIR /app\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\nCOPY . .\nCMD [\"uvicorn\", \"main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]","r":"Dockerfile = recipe for an image.","g":["dockerfile","docker_image","o_docker_cli","z_pip","port"],"fa":"A text file with step-by-step instructions to build a Docker image","cat":"ops"},{"id":"OPS-32","t":"m","l":1,"q":"What does `-p 8080:8000` mean in `docker run -p 8080:8000 myapp`?","o":["Use 8080 MB of memory for the container while it is running","Forward port 8080 of your computer to port 8000 of the container","Run 8080 copies of the container at the same time on one host","Limit the app inside the container to 8000 requests per second"],"a":1,"e":"The app inside the container listens on its own port 8000, which is isolated from your computer.\n`-p HOST:CONTAINER` publishes it: requests to http://localhost:8080 on your machine are forwarded to port 8000 in the container.\nInside the container, the app must listen on 0.0.0.0 (all interfaces), not only 127.0.0.1.","r":"-p host_port:container_port.","g":["port","container","o_docker_cli","interface"],"fa":"Forward port 8080 on your computer to port 8000 inside the container","cat":"ops"},{"id":"OPS-33","t":"m","l":1,"q":"What is Continuous Integration (CI)?","o":["Merging all the code of the whole team together once a month","Automatically building and testing every change pushed to the repo","Deploying directly from a developer laptop straight to production","Writing the documentation of each release before it is shipped"],"a":1,"e":"With CI, every push or pull request triggers an automated pipeline (GitHub Actions, GitLab CI): install, lint, run tests, build.\nIf something fails, the author knows within minutes, while the change is still fresh in their head, and broken code does not reach the main branch.\nDevelopers integrate small changes often instead of huge merges.","r":"CI = every change is built and tested automatically.","g":["ci","pipeline","repository","v_pull_request","git_branch"],"fa":"Automatically building and testing every change pushed to the repository, so problems are found quickly","cat":"ops"},{"id":"OPS-34","t":"m","l":1,"q":"What does 'running in the cloud' basically mean?","o":["The code of the app runs inside the browser of the user","Using servers and storage owned by a provider, rented on demand","Running the program without using any electricity at the office","Using only free and open source software for everything"],"a":1,"e":"Instead of buying and maintaining your own servers, you rent them by the hour or second and create them in minutes via a website or API.\nProviders also offer managed services (databases, queues, storage) so you don't operate them yourself.\nBenefits: scale up and down quickly, pay for what you use, global data centers.","r":"Cloud = rented, on-demand infrastructure and services.","g":["cloud","n_aws","n_gcp","z_database","z_server","api"],"fa":"Using computing resources (servers, storage, databases) owned and managed by a provider like AWS, Azure or GCP, rented on demand over the internet","cat":"ops"},{"id":"OPS-35","t":"m","l":1,"q":"Why read `DATABASE_URL` from an environment variable instead of writing it in the code?","o":["It is faster to read a value from the environment than from code","The same code runs in each environment with different values","Python requires that all the settings come from the environment","It encrypts the URL while the program is running in memory"],"a":1,"e":"Environment variables are values provided to a program by the system that runs it. In Python: `os.environ[\"DATABASE_URL\"]`.\nYour laptop, the staging server and production each set their own value, while the code stays identical.\nPasswords inside the URL never get committed to git.","r":"Settings and secrets → environment variables.","g":["env_var","secret","twelve_factor","z_variable","z_url","v_git"],"fa":"The same code can run in dev, staging and prod with different values, and secrets stay out of the code","cat":"ops"},{"id":"OPS-36","t":"m","l":1,"q":"What is Kubernetes mainly used for?","o":["Writing Python code that is going to run inside containers","Orchestrating containers across machines: scheduling, scaling, restarts","Replacing Git as the version control system for the code","Designing the databases that are used by the application"],"a":1,"e":"Running one container is easy. Running hundreds across many servers, keeping them alive, updating them without downtime and connecting them is hard.\nKubernetes (K8s) does this automatically: you describe the desired state ('3 copies of my API, version 2.1') and it keeps reality matching it.\nManaged versions: EKS (AWS), GKE (Google), AKS (Azure).","r":"Kubernetes = automatic manager for many containers.","g":["kubernetes","container","routing","api","o_ecs_eks","n_aws"],"fa":"Orchestrating containers across many machines: scheduling, scaling, restarting failed ones and routing traffic","cat":"ops"},{"id":"OPS-37","t":"m","l":1,"q":"What is a staging environment?","o":["The laptop of the developer who writes the code","A copy of production used to test changes before going live","The production database that real users use","A backup server that takes over after a failure"],"a":1,"e":"Typical environments: development (your machine), staging (production-like, for final checks) and production (real users).\nTesting in staging catches problems with real configuration, infrastructure and data volumes that don't appear locally.\nThe closer staging is to production, the more useful it is.","r":"Staging = rehearsal before production.","g":["staging","pipeline","ci","cd","z_deploy"],"fa":"A copy of production, as similar as possible, where changes are tested before going live","cat":"ops"},{"id":"OPS-38","t":"m","l":1,"q":"In a containerized app, where should application logs go?","o":["To a file inside the container, and nowhere else at all","To stdout or stderr, where the platform collects them","Nowhere, since logs are not needed for apps in production","By email to the team each time that an event happens"],"a":1,"e":"Files inside a container disappear when it is replaced, and with many containers you could never find them.\nWrite logs to stdout/stderr; Docker and Kubernetes capture them, and a logging stack (CloudWatch, ELK, Loki, Datadog) collects them centrally so you can search across all instances.\nStructured logs (JSON with fields like request_id) are easier to search.","r":"Containers: log to stdout, collect centrally.","g":["logs","twelve_factor","container","kubernetes","json"],"fa":"To standard output (stdout/stderr), where the platform collects and ships them to a logging system","cat":"ops"},{"id":"OPS-39","t":"m","l":1,"q":"What is SSH used for?","o":["Sending emails securely between two mail servers on a network","Logging in to a remote server and running commands over an encrypted link","Hosting websites on a server that runs somewhere in the cloud","Compressing files before they are sent over a slow network"],"a":1,"e":"`ssh user@server` opens an encrypted terminal session on a remote machine.\nAuthentication is usually with a key pair: your private key stays on your computer, the public key is installed on the server. That is safer than passwords.\nGit also uses SSH to push to GitHub.","r":"SSH = secure remote terminal.","g":["ssh","asymmetric","authn","z_server","v_git"],"fa":"Securely logging in to and running commands on a remote server over an encrypted connection","cat":"ops"},{"id":"OPS-40","t":"m","l":1,"q":"Which Docker commands list running containers and show a container's logs?","o":["`docker ps` and `docker logs <container>`","`docker list` and `docker show`","`docker images` and `docker run`","`docker build` and `docker push`"],"a":0,"e":"Everyday Docker commands:\n- `docker build -t myapp .`: build an image from a Dockerfile.\n- `docker run -d -p 8080:8080 --name web myapp`: start a container in the background.\n- `docker ps` (add `-a` for stopped ones): list containers.\n- `docker logs -f web`: follow the output.\n- `docker exec -it web sh`: open a shell inside it.\n- `docker stop web` / `docker rm web`: stop and remove it.\n- `docker images`: list local images.","r":"ps = list, logs = output, exec = shell inside.","g":["container","docker_image","o_docker_cli","dockerfile"],"cat":"ops"},{"id":"OPS-41","t":"m","l":2,"q":"What does this Dockerfile for a Spring Boot app do?","c":"FROM eclipse-temurin:21-jre\nWORKDIR /app\nCOPY target/app.jar app.jar\nEXPOSE 8080\nENTRYPOINT [\"java\", \"-jar\", \"app.jar\"]","o":["Java 21 base image, copies the JAR, documents 8080, runs `java -jar`","Compiles the Java source code inside the image when it is built","Opens port 8080 on the host automatically when the app runs","Installs Maven and runs the tests when the image is being built"],"a":0,"e":"Line by line:\n- `FROM`: start from an existing image that contains a Java 21 runtime (JRE, enough to run, smaller than the JDK).\n- `WORKDIR`: working folder inside the image.\n- `COPY`: put the already built JAR (from `mvn package`) into the image.\n- `EXPOSE 8080`: only DOCUMENTS the port; you still need `docker run -p 8080:8080` to publish it.\n- `ENTRYPOINT`: the command that runs when the container starts.\nIt does not compile anything; a multi-stage build can do the Maven build in a first stage.","r":"EXPOSE documents the port; -p publishes it.","g":["dockerfile","docker_image","j_jdk","sp_spring_boot","n_javac","multi_stage"],"fa":"Starts from a base image with Java 21, copies the built JAR, documents port 8080 and runs the app with `java -jar`","cat":"ops"},{"id":"OPS-42","t":"m","l":2,"q":"In Kubernetes, what is the difference between a ConfigMap and a Secret?","o":["There is no difference between them, apart from the name","ConfigMap holds plain config; Secret holds sensitive values (base64)","ConfigMap stores container images; Secret stores the pod logs","A Secret is read faster, because it is always kept in memory"],"a":1,"e":"Both inject settings into Pods as environment variables or mounted files, so you do not bake them into the image.\n- ConfigMap: plain settings (URLs, feature switches, log level).\n- Secret: passwords, API keys, certificates. Access can be restricted with RBAC.\nImportant: Secrets are only base64-encoded by default, which is not encryption. Enable encryption at rest or use an external manager (AWS Secrets Manager, Azure Key Vault) with a CSI driver or External Secrets.","r":"ConfigMap = config. Secret = sensitive config (still protect it).","g":["k8s_secret","o_configmap","encryption","kubernetes","env_var","pod"],"fa":"ConfigMap holds non-sensitive configuration; Secret holds sensitive values (passwords, tokens) with extra handling, but is only base64-encoded unless encryption at rest is enabled","cat":"ops"},{"id":"OPS-43","t":"m","l":1,"q":"What are Kubernetes namespaces for?","o":["To encrypt the traffic that moves between the pods of the cluster","To split one cluster into sections with names, quotas and permissions","To store the container images that belong to each team","To schedule jobs at fixed times of the day inside the cluster"],"a":1,"e":"A namespace is a folder-like boundary inside a cluster. Two teams or environments can both have a Service called `api` without clashing.\nYou can attach resource quotas and access rules (RBAC) per namespace. Default namespaces: `default`, `kube-system` (cluster components).\nUse `kubectl get pods -n staging` to choose one.","r":"Namespace = logical partition of a cluster.","g":["kubernetes","o_namespace","pod","o_kubectl","n_rbac"],"fa":"To divide one cluster into logical virtual sections (e.g. dev, staging, team-a) with separate names, quotas and permissions","cat":"ops"},{"id":"OPS-44","t":"m","l":2,"q":"What are the Kubernetes Service types ClusterIP, NodePort and LoadBalancer, and what is an Ingress?","o":["ClusterIP: internal. NodePort: node. LoadBalancer: external. Ingress: HTTP","All four are the same object, but written with different names","ClusterIP is public to the internet and LoadBalancer is internal only","Ingress stores the data of the application inside the whole cluster"],"a":0,"e":"A Service gives Pods a stable address. Types:\n- ClusterIP (default): internal-only virtual IP.\n- NodePort: exposes the Service on a high port (30000-32767) on each node.\n- LoadBalancer: asks the cloud (AWS/Azure) to create an external load balancer.\nAn Ingress is a set of HTTP(S) rules (`shop.example.com/api` to service A, `/web` to service B), implemented by an Ingress Controller (NGINX, AWS ALB controller, Azure Application Gateway). One load balancer can serve many services.","r":"ClusterIP internal, LoadBalancer external, Ingress = HTTP routing rules.","g":["service_k8s","o_ingress","http","load_balancer","kubernetes","n_aws"],"fa":"ClusterIP: reachable only inside the cluster (default). NodePort: opens a port on every node. LoadBalancer: gets a cloud load balancer. Ingress: HTTP(S) routing by host/path to Services","cat":"ops"},{"id":"OPS-45","t":"m","l":1,"q":"Which `kubectl` commands apply a manifest, list Pods and read a Pod's logs?","o":["`kubectl apply -f x.yaml`, `get pods`, `logs <pod>`","`kubectl run x.yaml`, `kubectl list`, `kubectl show`","`kubectl build`, `kubectl push`, `kubectl read`","`kubectl start`, `kubectl stop`, `kubectl delete`"],"a":0,"e":"`kubectl` is the command line for Kubernetes.\n- `kubectl apply -f deployment.yaml`: create or update objects from a file (declarative).\n- `kubectl get pods` (also `deploy`, `svc`, `-A` for all namespaces).\n- `kubectl describe pod <name>`: details and events (why it is not starting).\n- `kubectl logs <pod>` (`-f` follow, `--previous` for the last crashed container).\n- `kubectl exec -it <pod> -- sh`: shell inside.\n- `kubectl rollout undo deployment/<name>`: roll back.","r":"apply, get, describe, logs.","g":["kubernetes","o_kubectl","pod","container","object"],"fa":"`kubectl apply -f x.yaml`, `kubectl get pods`, `kubectl logs <pod>`","cat":"ops"},{"id":"OPS-46","t":"m","l":2,"q":"What does this manifest declare?","c":"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: api\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: api\n  template:\n    metadata:\n      labels:\n        app: api\n    spec:\n      containers:\n        - name: api\n          image: myrepo/api:1.4.2\n          ports:\n            - containerPort: 8080","o":["Keep 3 Pods of `myrepo/api:1.4.2`, tied to labels `app: api`","Run 8080 copies of the app on every node of the cluster","Create a database named api that has three replicas","Open port 3 on the node so that the app can be reached"],"a":0,"e":"A Deployment is a desired-state declaration: \"I want 3 replicas of this Pod template\".\n`template` describes each Pod (labels and containers). `selector.matchLabels` tells the Deployment which Pods belong to it, so the labels in `template.metadata.labels` must match.\nIf a Pod dies, Kubernetes creates another to keep 3. Changing the image tag triggers a rolling update.","r":"Deployment = desired replicas + Pod template; labels link them.","g":["deployment_k8s","pod","o_yaml","kubernetes"],"fa":"Keep 3 Pods running from image `myrepo/api:1.4.2`; the `selector` ties the Deployment to Pods labeled `app: api`","cat":"ops"},{"id":"OPS-47","t":"m","l":2,"q":"When would you use a StatefulSet, a DaemonSet, a Job or a CronJob instead of a Deployment?","o":["StatefulSet: stateful. DaemonSet: per node. Job: once. CronJob: scheduled","They are all identical, and any of them can replace a Deployment","StatefulSet is for stateless apps and Job is meant for databases","DaemonSet creates databases and CronJob scales Pods up and down"],"a":0,"e":"Deployment fits stateless apps: any replica is interchangeable.\n- StatefulSet: Pods with stable names (`db-0`, `db-1`) and their own persistent volumes; for databases and brokers.\n- DaemonSet: ensures one Pod runs on each node: log collectors, monitoring agents.\n- Job: runs until it finishes successfully (a migration, a batch import).\n- CronJob: creates Jobs on a cron schedule (nightly report).","r":"Stateless = Deployment. Stateful = StatefulSet. Per node = DaemonSet. Once = Job.","g":["deployment_k8s","o_statefulset","o_kubectl","o_yaml","kubernetes","o_helm"],"fa":"StatefulSet: stateful apps needing stable identity/storage (databases). DaemonSet: one Pod per node (log agents). Job: run a task to completion. CronJob: run a Job on a schedule","cat":"ops"},{"id":"OPS-48","t":"m","l":2,"q":"A Pod shows `CrashLoopBackOff`. What does it mean and how do you start debugging?","o":["The container keeps crashing and restarting; read `logs --previous`","The node is out of disk space and cannot start pods","The image is still being downloaded from the registry","The Service has no IP address, so the Pod cannot start"],"a":0,"e":"CrashLoopBackOff = the container starts, exits with an error, Kubernetes restarts it, and waits longer after each failure.\nTypical causes: application error at startup (bad config, missing env var), cannot connect to the database, wrong command, out of memory (OOMKilled) or a failing liveness probe.\nSteps: `kubectl logs <pod> --previous` (output of the crashed run), `kubectl describe pod <pod>` (events and exit code), check ConfigMap/Secret values and resource limits.","r":"CrashLoopBackOff: read logs --previous and describe.","g":["pod","o_crashloop","exit_code","o_kubectl","kubernetes","o_configmap"],"fa":"The container keeps starting and crashing; Kubernetes retries with growing delays. Check `kubectl logs --previous` and `kubectl describe pod`","cat":"ops"},{"id":"OPS-49","t":"m","l":2,"q":"What is the difference between Kubernetes resource `requests` and `limits`?","o":["Requests are reserved for scheduling; limits are the maximum allowed","They are the same value, just written in two different places","Limits are the minimum amounts and requests are the maximums","Requests are only used for storage and never for CPU or memory"],"a":0,"e":"For each container you can set CPU and memory.\n- `requests`: what the scheduler reserves; Kubernetes places the Pod on a node that has this much free.\n- `limits`: the ceiling. If a container exceeds its memory limit it is killed (OOMKilled, exit code 137). If it exceeds its CPU limit it is slowed down (throttled).\nWithout requests the scheduler cannot plan well; the HPA also uses requests to calculate CPU percentage.\nFor the JVM, make sure the heap fits inside the memory limit.","ec":"resources:\n  requests: { cpu: \"250m\", memory: \"512Mi\" }\n  limits:   { cpu: \"1\",    memory: \"1Gi\" }","r":"Request = guaranteed for scheduling. Limit = hard ceiling.","g":["o_resources","oom","n_cpu","kubernetes","throttle","exit_code"],"fa":"Requests: the amount reserved for scheduling (guaranteed); limits: the maximum a container may use (exceeding memory kills it, exceeding CPU throttles it)","cat":"ops"},{"id":"OPS-50","t":"m","l":2,"q":"What is Helm?","o":["A container runtime that runs the images on each node","The Kubernetes package manager: charts with templates and values","A monitoring tool that collects metrics from the whole cluster","A Git client that is used for managing the manifests of a project"],"a":1,"e":"Applications in Kubernetes need many YAML files (Deployment, Service, Ingress, ConfigMap). Helm packages them as a chart with templates and a `values.yaml`.\n`helm install myapp ./chart -f values-prod.yaml` deploys it; `helm upgrade` updates; `helm rollback` goes back.\nIt avoids copy-pasting manifests between environments, since only the values change.","r":"Helm = chart + values = installable, upgradable Kubernetes app.","g":["o_helm","kubernetes","o_configmap","rollback","o_ingress","o_yaml"],"fa":"The package manager for Kubernetes: a chart bundles templated manifests so you install and upgrade an app with values per environment","cat":"ops"},{"id":"OPS-51","t":"m","l":1,"q":"What is a container registry, and what are examples?","o":["A place to store and share container images, like Docker Hub or ECR","A list of the containers that are running on a host machine","A firewall that filters the traffic going to the containers","A source code repository that stores the Dockerfiles"],"a":0,"e":"After `docker build` the image exists only on your machine. You `docker push` it to a registry so servers and Kubernetes can `pull` it.\nPublic: Docker Hub. Private cloud registries: AWS ECR, Azure ACR, Google Artifact Registry, GitHub Container Registry.\nImages are identified as `registry/name:tag`. Prefer specific tags (`1.4.2`) over `latest`, so deployments are reproducible.","r":"Registry = shared storage for images (push/pull).","g":["docker_image","o_registry","n_aws","n_ecr_acr","container","o_docker_cli"],"fa":"A place to store and distribute container images: Docker Hub, AWS ECR, Azure Container Registry (ACR), GitHub Container Registry","cat":"ops"},{"id":"OPS-52","t":"m","l":2,"q":"What are PersistentVolumes (PV) and PersistentVolumeClaims (PVC)?","o":["A PV is cluster storage; a PVC is a Pod's request that binds to a PV","Two kinds of network policy that control traffic between Pods","Two types of Pod: one for storage and one for compute work","Backup tools that copy the state of a cluster to remote storage"],"a":0,"e":"Container filesystems disappear when a Pod is replaced. For durable data (databases, uploads) Kubernetes separates the storage from the Pod:\n- PV: actual storage (cloud disk like EBS or Azure Disk, NFS).\n- PVC: \"I need 10 GiB, ReadWriteOnce\". Kubernetes finds or dynamically provisions a PV through a StorageClass and attaches it.\nThe Pod mounts the claim. Managed databases (RDS, Azure SQL) are often preferable to running databases in Kubernetes.","r":"PVC asks, PV provides, data outlives Pods.","g":["volume","o_pvc","pod","kubernetes","sql","o_rds_dynamo"],"fa":"A PV is a piece of storage in the cluster; a PVC is a Pod's request for storage that Kubernetes binds to a PV, so data survives Pod restarts","cat":"ops"},{"id":"OPS-53","t":"m","l":1,"q":"Which AWS service is closest to a rented virtual server, and which runs code without managing servers?","o":["EC2 is the virtual server; Lambda runs code without managing servers","Lambda is the virtual server; EC2 runs code without managing servers","S3 is the virtual server; RDS runs code without managing servers","IAM is the virtual server; VPC runs code without managing servers"],"a":0,"e":"EC2 (Elastic Compute Cloud): virtual machines you choose, configure and patch.\nLambda: serverless functions; you upload code, AWS runs it on events and bills per execution.\nIn between: ECS/EKS (containers), Fargate (containers without managing servers), Elastic Beanstalk (PaaS).\nThe more managed, the less control but less operations work.","r":"EC2 = virtual machine. Lambda = serverless function.","g":["o_ec2","serverless","n_aws","vm","lambda","o_iaas"],"fa":"EC2 is the virtual server; Lambda runs functions without servers","cat":"ops"},{"id":"OPS-54","t":"m","l":2,"q":"ECS vs EKS vs Fargate: what do they mean?","o":["ECS is the AWS orchestrator, EKS is managed Kubernetes, Fargate is serverless","They are identical services that AWS sells under three names","EKS is a database service; ECS is object storage; Fargate is a CDN","Fargate is a Lambda alternative that is used only for databases"],"a":0,"e":"All three run containers on AWS.\n- ECS (Elastic Container Service): simpler, AWS-specific orchestrator.\n- EKS (Elastic Kubernetes Service): managed Kubernetes control plane; portable skills across clouds.\n- Fargate: the \"serverless\" launch type: you define CPU/memory per task or Pod, AWS provides the machines.\nAzure equivalents: AKS (Kubernetes), Azure Container Apps and Azure Container Instances (serverless containers).","r":"ECS = AWS orchestrator, EKS = Kubernetes, Fargate = no nodes to manage.","g":["o_ecs_eks","kubernetes","n_aws","serverless","service_k8s","pod"],"fa":"ECS: AWS's own container orchestrator. EKS: managed Kubernetes. Fargate: serverless compute for containers, usable with ECS or EKS so you do not manage nodes","cat":"ops"},{"id":"OPS-55","t":"m","l":2,"q":"RDS vs DynamoDB: when do you choose each?","o":["RDS is managed SQL; DynamoDB is serverless NoSQL for simple, huge access","They are identical services that differ only in their price","RDS is a NoSQL store; DynamoDB is a relational SQL database","DynamoDB supports joins and complex SQL queries like RDS does"],"a":0,"e":"RDS runs engines like PostgreSQL, MySQL, SQL Server or Oracle for you (backups, patching, failover) while you keep SQL, transactions and joins. Choose it for most business apps.\nDynamoDB is a fully managed NoSQL store that scales to huge traffic with single-digit millisecond reads, but you design tables around known access patterns (partition key) and have no joins.\nAzure equivalents: Azure SQL / Azure Database for PostgreSQL, and Cosmos DB.","r":"Relational and flexible queries: RDS. Massive simple key lookups: DynamoDB.","g":["o_rds_dynamo","nosql","sql","d_relational","serverless","transaction"],"fa":"RDS: managed relational databases (PostgreSQL, MySQL...) with SQL and joins. DynamoDB: serverless key-value/document NoSQL with very high scale and simple access patterns","cat":"ops"},{"id":"OPS-56","t":"m","l":2,"q":"In AWS networking, what is a VPC and the difference between a public and a private subnet?","o":["A VPC is your private AWS network; public subnets route to an Internet Gateway","A VPC is a type of database; subnets are used to store files","Public subnets are encrypted; private subnets have no encryption","A VPC is a CDN; public and private subnets are cache layers"],"a":0,"e":"A VPC (Virtual Private Cloud) is an isolated network you define with an IP range (CIDR, e.g. `10.0.0.0/16`), divided into subnets in different Availability Zones.\n- Public subnet: route table sends `0.0.0.0/0` to an Internet Gateway; resources can have public IPs (load balancers, bastion hosts).\n- Private subnet: no direct inbound from the internet; outbound goes through a NAT Gateway placed in a public subnet. Put app servers and databases here.\nAzure equivalent: Virtual Network (VNet) and subnets.","r":"Public subnet = route to Internet Gateway. Private = no direct route.","g":["o_vpc","o_cidr","n_aws","o_nat","availability_zone","load_balancer"],"fa":"A VPC is your private virtual network in AWS; a public subnet has a route to an Internet Gateway, a private subnet does not (it reaches the internet only through a NAT Gateway)","cat":"ops"},{"id":"OPS-57","t":"m","l":2,"q":"Security Group vs Network ACL (AWS): which statement is correct?","o":["Security Groups are stateful, allow-only; NACLs are stateless, per subnet","Security Groups are stateless; NACLs are stateful and per instance","Both are identical and only differ in the console they use","Security Groups only filter outbound traffic from an instance"],"a":0,"e":"Security Group: a virtual firewall around an instance/network interface. Stateful: if inbound traffic is allowed, the response is automatically allowed. Only allow rules; everything else is denied.\nNetwork ACL: a firewall at the subnet boundary. Stateless: you must allow return traffic explicitly. Has numbered allow and deny rules.\nMost day-to-day control is done with Security Groups. Azure equivalent: Network Security Groups (NSG).","r":"Security group = stateful, per resource. NACL = stateless, per subnet.","g":["o_security_group","o_vpc","o_cidr","iam","z_firewall","n_aws"],"fa":"Security Groups are stateful, attached to resources, allow-only rules; NACLs are stateless, apply at subnet level and support allow and deny rules","cat":"ops"},{"id":"OPS-58","t":"m","l":2,"q":"What is the difference between an Application Load Balancer (ALB) and a Network Load Balancer (NLB)?","o":["ALB works at layer 7 with path routing; NLB works at layer 4 for speed","They are identical and only differ in the price of each hour","ALB is meant for databases; NLB is meant for web traffic","NLB understands URLs and paths; ALB does not understand them"],"a":0,"e":"Layers refer to the network model: layer 4 = transport (TCP/UDP ports), layer 7 = application (HTTP).\n- ALB: understands HTTP, so it can route `/api/*` to one service and `/web/*` to another, terminate TLS, and integrate with WAF.\n- NLB: forwards TCP/UDP connections without reading HTTP; ultra-low latency, millions of requests, fixed IPs.\nAzure equivalents: Application Gateway (layer 7) and Azure Load Balancer (layer 4); Azure Front Door is a global layer 7.","r":"ALB = L7 HTTP routing. NLB = L4 TCP speed.","g":["load_balancer","o_l4_l7","n_alb_nlb","http","n_tcp","n_udp"],"fa":"ALB works at layer 7 (HTTP/HTTPS) with path/host routing; NLB works at layer 4 (TCP/UDP) for very high performance and static IPs","cat":"ops"},{"id":"OPS-59","t":"m","l":1,"q":"Which pairs of AWS and Azure services are equivalent?","o":["EC2 = VMs, S3 = Blob Storage, Lambda = Functions, EKS = AKS","EC2 = Blob Storage, S3 = Azure Functions, Lambda = AKS","S3 = AKS, Lambda = Virtual Machines, EKS = Blob Storage","They have no equivalents, because each cloud is different"],"a":0,"e":"Both clouds offer similar building blocks with different names:\n- Compute: EC2 / Virtual Machines; Lambda / Functions; EKS / AKS; Elastic Beanstalk / App Service.\n- Storage: S3 / Blob Storage; EBS / Managed Disks.\n- Databases: RDS / Azure SQL & Azure Database for PostgreSQL; DynamoDB / Cosmos DB.\n- Network: VPC / VNet; Security Group / NSG; Route 53 / Azure DNS; CloudFront / Azure CDN & Front Door.\n- Identity: IAM / Entra ID (formerly Azure AD) + Azure RBAC.\n- Messaging: SQS / Storage Queues or Service Bus; SNS / Event Grid.\n- Monitoring: CloudWatch / Azure Monitor & Application Insights.\n- Secrets: Secrets Manager / Key Vault. Registry: ECR / ACR.","r":"Same ideas, different names. Learn the mapping table.","g":["o_azure_map","cloud","vm","n_aks","s3","o_ec2"],"fa":"EC2 = Azure Virtual Machines; S3 = Blob Storage; Lambda = Azure Functions; EKS = AKS; IAM = Entra ID + Azure RBAC","cat":"ops"},{"id":"OPS-60","t":"m","l":2,"q":"How is Azure organized: subscription, resource group and resource?","o":["A subscription is for billing; a resource group holds resources","A resource group contains subscriptions, and subscriptions hold resources","Resources contain resource groups, and groups contain subscriptions","They are all the same thing, named at different levels"],"a":0,"e":"Hierarchy: Management group, Subscription, Resource group, Resource.\n- Subscription: billing and quota boundary.\n- Resource group: a folder for resources that are deployed, managed and deleted together (an app and its database).\n- Resource: a concrete thing: VM, VNet, storage account, AKS cluster.\nPermissions (Azure RBAC) and policies can be applied at any level and are inherited downward. Deleting a resource group deletes everything in it.","r":"Subscription (billing) > resource group (lifecycle folder) > resources.","g":["o_azure_rg","vm","o_vpc","n_rbac","n_aks"],"fa":"A subscription is a billing and access boundary; a resource group is a logical container for related resources that share a lifecycle; a resource is a single service instance (VM, storage account)","cat":"ops"},{"id":"OPS-61","t":"m","l":3,"q":"What is an Azure Managed Identity (and the AWS equivalent for workloads)?","o":["An identity Azure manages so apps reach services without stored secrets","A user account for humans that signs in with a password","A type of virtual network that connects two subscriptions","A backup policy that protects the keys of a subscription"],"a":0,"e":"Hard-coded secrets are a leading cause of breaches. With a managed identity, the resource (VM, App Service, AKS pod) gets an identity in Entra ID and requests short-lived tokens automatically. You grant that identity permissions (for example read access to a Key Vault or Blob container) through Azure RBAC.\nNo password or connection string exists in code or config to leak or rotate.\nAWS: attach an IAM role to the EC2 instance, ECS task or Lambda function.","r":"Managed identity / IAM role = credentials without secrets.","g":["o_managed_identity","iam","least_privilege","n_aws","s_kms","n_rbac"],"fa":"An identity automatically managed by Azure that an app uses to access other Azure services without storing passwords or keys; AWS uses IAM roles for the same goal","cat":"ops"},{"id":"OPS-62","t":"m","l":1,"q":"What does the CIDR notation `10.0.1.0/24` mean?","o":["A network with 24 fixed bits and 8 host bits: 256 addresses","A group of 24 servers that share the same address","A network that has exactly 24 addresses in total","Port 24 on the host whose address is 10.0.1.0"],"a":0,"e":"An IPv4 address has 32 bits. `/24` means the first 24 bits identify the network and the remaining 8 bits identify devices: 2^8 = 256 addresses (a few are reserved; AWS reserves 5 per subnet).\nQuick table: `/16` = 65,536 addresses, `/24` = 256, `/28` = 16. A smaller number after the slash means a bigger network.\nYou use CIDR ranges to define VPCs, subnets and firewall rules, and ranges must not overlap if you want to connect networks.","r":"/N = N fixed bits. /24 = 256 addresses.","g":["o_cidr","z_firewall","n_aws","table"],"fa":"A network whose first 24 bits are fixed, leaving 8 bits for hosts: 256 addresses","cat":"ops"},{"id":"OPS-63","t":"m","l":1,"q":"What is the difference between a public IP, a private IP and NAT?","o":["Public IPs reach the internet; private IPs stay inside; NAT translates","They are identical and differ only in the way they are written","Private IPs are faster than public IPs in every network","NAT encrypts the data that goes through the router"],"a":0,"e":"Private ranges (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`) are not routed on the public internet; many networks reuse them.\nA NAT gateway translates the private source address of outgoing traffic into a public address, and maps replies back. So servers in a private subnet can download updates, but outsiders cannot start connections to them.","r":"Private inside, public outside, NAT translates.","g":["o_nat","o_cidr","n_ip","z_server"],"fa":"Public IPs are reachable from the internet; private IPs (10.x, 172.16-31.x, 192.168.x) are only used inside a network; NAT lets private hosts reach the internet by translating to a public address","cat":"ops"},{"id":"OPS-64","t":"m","l":2,"q":"What is the difference between DNS record types A, CNAME and MX?","o":["A maps a name to an IPv4 address; CNAME is an alias; MX is for email","A is used for email delivery and MX is used for IPv4 addresses","CNAME maps a name to an IP, while A maps a name to another name","They are all identical and any of them can replace the others"],"a":0,"e":"DNS translates names into data:\n- A (and AAAA for IPv6): `api.example.com` to `203.0.113.10`.\n- CNAME: `www.example.com` is an alias of `example.com` (or of a load balancer's DNS name).\n- MX: mail servers for the domain.\n- TXT: free text such as domain verification and SPF.\nA CNAME cannot sit at the zone apex (`example.com` itself); clouds provide alias records for that. Services: Route 53 (AWS), Azure DNS.","r":"A = name to IP. CNAME = name to name. MX = mail.","g":["dns","o_dns_records","n_ip","load_balancer","n_aws"],"fa":"A maps a name to an IPv4 address; CNAME maps a name to another name (alias); MX tells where to deliver email","cat":"ops"},{"id":"OPS-65","t":"m","l":3,"q":"How can a private app in your VPC/VNet reach a cloud service (e.g. S3 or Azure Storage) without going over the public internet?","o":["With private endpoints: PrivateLink gives the service a private IP","It is impossible, since cloud services are always public","By disabling the firewall so that traffic can flow freely","By giving the app a public IP and using the internet"],"a":0,"e":"By default, calls to S3 or Azure Storage go to public endpoints. For security and compliance you can keep traffic on the provider's private network:\n- AWS: VPC endpoints (Gateway endpoints for S3/DynamoDB, Interface endpoints through PrivateLink for many services).\n- Azure: Private Endpoint (Private Link) that places a private IP of the service in your VNet.\nCombined with firewall rules that block public access, data never crosses the internet.","r":"Private endpoints = service reachable on a private IP.","g":["o_private_link","o_vpc","n_ip","s3","n_aws","o_rds_dynamo"],"fa":"Private endpoints: AWS PrivateLink / VPC endpoints and Azure Private Link give the service a private IP inside your network","cat":"ops"},{"id":"OPS-66","t":"m","l":3,"q":"How do you connect an on-premises network (a company office or data center) to your cloud network?","o":["A site-to-site VPN, or a private line like Direct Connect or ExpressRoute","By emailing the configuration files to the cloud provider","Only with a USB drive that is carried to the data center","It is not possible to connect them, so data is copied by hand"],"a":0,"e":"Hybrid cloud connects existing infrastructure with the cloud.\n- Site-to-site VPN: an encrypted tunnel over the public internet. Quick and cheap, variable latency (AWS Site-to-Site VPN, Azure VPN Gateway).\n- Dedicated connection: a private physical circuit from a provider (AWS Direct Connect, Azure ExpressRoute): more predictable latency and bandwidth, more cost and lead time.\nNetwork ranges must not overlap. Hub-and-spoke designs (AWS Transit Gateway, Azure Virtual WAN) manage many networks.","r":"VPN = encrypted over internet. Direct Connect/ExpressRoute = private line.","g":["o_hybrid","o_vpc","tls","o_nat","o_dns_records","n_vpn"],"fa":"Site-to-site VPN over the internet (encrypted), or a dedicated private line: AWS Direct Connect / Azure ExpressRoute","cat":"ops"},{"id":"OPS-67","t":"m","l":1,"q":"What is the shared responsibility model in the cloud?","o":["The provider secures the cloud; you secure what you put in it","The provider is responsible for everything that runs in the cloud","The customer is responsible for the data centers and hardware","There is no division of duties, so each case is negotiated"],"a":0,"e":"Security of the cloud (provider): physical data centers, hardware, hypervisor, managed service internals.\nSecurity in the cloud (you): who has access (IAM), how storage and networks are configured (public S3 buckets are a classic mistake), patching your VMs, encrypting data, your application code.\nThe more managed the service (SaaS over IaaS), the more the provider handles.","r":"Provider secures the cloud; you secure what is in it.","g":["o_shared_resp","cloud","o_iaas","vm","iam","s3"],"fa":"The provider secures the cloud itself (hardware, data centers, core services); you secure what you put in it (data, identities, configuration, your code)","cat":"ops"},{"id":"OPS-68","t":"m","l":1,"q":"IaaS, PaaS and SaaS: which examples match?","o":["IaaS: EC2 or Azure VM. PaaS: App Service. SaaS: Microsoft 365","IaaS: Gmail. PaaS: EC2. SaaS: a VPC network","All three terms mean the same thing: serverless computing","IaaS: Lambda. PaaS: S3. SaaS: a virtual machine"],"a":0,"e":"The service models differ by how much the provider manages for you:\n- IaaS (Infrastructure): you rent virtual machines, storage and networks; you manage OS and apps.\n- PaaS (Platform): you deploy code and the platform manages servers, scaling and patching.\n- SaaS (Software): a finished application you just use.\nServerless (Lambda/Functions) is an even higher level of PaaS: you only provide functions.","r":"IaaS = servers, PaaS = platform for your code, SaaS = finished app.","g":["o_iaas","cloud","o_ec2","vm","serverless","n_os"],"fa":"IaaS: EC2/Azure VM. PaaS: Elastic Beanstalk/Azure App Service. SaaS: Microsoft 365/Gmail","cat":"ops"},{"id":"OPS-69","t":"m","l":2,"q":"Which native Infrastructure-as-Code tools exist for each cloud?","o":["CloudFormation or CDK for AWS, Bicep or ARM for Azure, Terraform for both","Only Terraform exists, and the clouds have no tools of their own","Excel and Word templates are used to describe the infrastructure","Jenkins only, because it builds the infrastructure from pipelines"],"a":0,"e":"Each cloud has its own IaC language: CloudFormation (YAML/JSON, plus the CDK in real programming languages) for AWS, and ARM templates or the simpler Bicep for Azure.\nTerraform (and OpenTofu) is cloud-neutral and popular for multi-cloud or when one tool for all providers is preferred.\nIaC means you review infrastructure changes in pull requests and can recreate environments reliably.","r":"CloudFormation (AWS), Bicep/ARM (Azure), Terraform (any).","g":["iac","terraform","n_aws","v_pull_request","json","o_yaml"],"fa":"AWS CloudFormation (and CDK); Azure ARM templates / Bicep; Terraform works on both","cat":"ops"},{"id":"OPS-70","t":"m","l":2,"q":"Which CI/CD tools are commonly used with Java projects?","o":["Jenkins, GitHub Actions, GitLab CI, Azure DevOps Pipelines","Photoshop, Excel, Word, PowerPoint and Visio documents","Only Docker, since it builds and deploys every project","Only Maven, since it builds and deploys every Java project"],"a":0,"e":"CI/CD tools run your pipeline on every push: build with Maven, run tests, build a Docker image, push it to a registry, deploy to Kubernetes or a cloud service.\n- Jenkins: self-hosted, very flexible, plugins.\n- GitHub Actions: pipelines defined in `.github/workflows/*.yml`, integrated with GitHub.\n- GitLab CI: `.gitlab-ci.yml`.\n- Azure DevOps Pipelines: `azure-pipelines.yml`, common in Azure shops.\nAll express the pipeline as code stored in the repository.","r":"Pipeline as code: Jenkins, GitHub Actions, GitLab CI, Azure DevOps.","g":["ci","pipeline","o_cicd_tools","cd","v_maven","docker_image"],"cat":"ops"},{"id":"OPS-71","t":"m","l":3,"q":"How do you make a web service highly available across failures in AWS or Azure?","o":["Two or more instances in different zones behind a load balancer, plus a multi-AZ DB","One large server with plenty of CPU and memory placed in a single zone","Daily backups only, restored by hand after any failure happens","Disable the health checks so that no instance is ever removed"],"a":0,"e":"High availability means the service keeps working when one component or data center fails.\n- Multiple instances/Pods across 2+ Availability Zones (Azure: availability zones too).\n- Load balancer with health checks removes unhealthy instances automatically.\n- Stateless app servers (session in Redis or a token), autoscaling to replace failed nodes.\n- Database: multi-AZ replicas with automatic failover (RDS Multi-AZ, Azure zone-redundant).\n- Regions: add a second region for disaster recovery (RTO/RPO targets).","r":"2+ zones + load balancer + health checks + replicated database.","g":["availability_zone","high_availability","load_balancer","n_aws","autoscaling","failover"],"fa":"Run at least two instances in different Availability Zones behind a load balancer with health checks, use a multi-AZ managed database, and avoid single points of failure","cat":"ops"},{"id":"OPS-72","t":"f","l":2,"q":"You have a Spring Boot service. Describe how you would containerize it and run it on Kubernetes in AWS or Azure.","a":"- Build: `mvn clean package` creates a JAR in CI; write a Dockerfile (or multi-stage build) from a small JRE image; run as a non-root user.\n- Push the image to a registry (ECR or ACR) with a version tag, never rely on `latest`.\n- Kubernetes: Deployment (replicas, resource requests/limits, readiness and liveness probes pointing to `/actuator/health`), Service (ClusterIP) and Ingress for HTTP.\n- Config: ConfigMap for settings, Secret or external secret manager for passwords; Spring profile via environment variable.\n- Scaling: HorizontalPodAutoscaler on CPU or custom metrics.\n- Cloud: EKS (AWS) or AKS (Azure), managed database (RDS or Azure SQL), identities via IAM role or managed identity.\n- Observability: logs to stdout, metrics through Actuator and Prometheus, alerts.","g":["kubernetes","n_aws","env_var","multi_stage","n_mvn_cmds","sp_actuator","o_managed_identity","sp_profile"],"cat":"ops"},{"id":"OPS-73","t":"f","l":2,"q":"How do you choose between VMs, containers (Kubernetes) and serverless?","a":"- VMs (EC2, Azure VM): full control, legacy apps, special OS needs; you patch and scale them.\n- Containers on Kubernetes (EKS/AKS): many services, portability, fine control over scaling and rollout; operational complexity.\n- Simpler container services (ECS/Fargate, Azure Container Apps, App Service): less operations work for typical web APIs.\n- Serverless (Lambda, Azure Functions): event-driven, spiky or low traffic, pay per use; limits on runtime, cold starts, harder local testing.\n- Decide by: team skills, traffic pattern, state and latency needs, cost model, vendor lock-in tolerance.\n- Answer style: start simple, move to more control only when a need appears.","g":["kubernetes","serverless","vm","o_ec2","o_ecs_eks","n_aks","n_os"],"cat":"ops"},{"id":"OPS-74","t":"f","l":1,"q":"Explain the main building blocks of cloud networking.","a":"- Region and Availability Zones: geography and isolated data centers inside it.\n- VPC / VNet: your private network, defined by a CIDR range, split into subnets.\n- Public vs private subnets: internet gateway route vs NAT for outbound only.\n- Firewalls: Security Groups / NSGs (per resource, stateful), NACLs (per subnet, stateless).\n- Load balancers: layer 4 (NLB, Azure LB) and layer 7 (ALB, Application Gateway).\n- DNS: Route 53 / Azure DNS; CDN: CloudFront / Azure CDN.\n- Private connectivity: PrivateLink / Private Endpoint; hybrid: VPN, Direct Connect / ExpressRoute; peering to join networks.","g":["cdn","dns","availability_zone","z_region_az","o_security_group","load_balancer","o_private_link","o_vpc"],"cat":"ops"},{"id":"OPS-75","t":"m","l":0,"q":"What does 'deploy' mean in software?","o":["Put a new version of the app on a server so users can use it","Delete the old code from the repository after a release","Write the first line of code of a new project","Print the source code for the team to review"],"a":0,"e":"Code on your laptop is only useful to you. Deploying means installing or updating the application in an environment where it runs for others: a test environment (staging) or production.\nModern teams automate this with CI/CD pipelines, so a merged change can reach a server with little manual work.\nTypical environments: dev (your machine), test/staging, production.","r":"Deploy = publish a version so it runs somewhere real.","g":["z_deploy","cd","pipeline","z_server","ci"],"fa":"Put a new version of the application on a server or cloud environment so users can use it","cat":"ops"},{"id":"OPS-76","t":"m","l":0,"q":"What is a terminal (command line) and what is a shell?","o":["The terminal is a text window; the shell (Bash, Zsh) interprets commands","A terminal is a physical keyboard; a shell is its protective cover","A terminal is a web browser; a shell is a saved bookmark","A terminal is a database client; a shell is a stored query"],"a":0,"e":"Most developer tools (git, mvn, docker, kubectl) are used from the terminal, because commands can be repeated, scripted and automated.\nBasic commands in Linux/macOS: `pwd` (where am I), `ls` (list files), `cd folder` (enter a folder), `cat file` (show a file).\nDon't memorize everything: learn the commands you use daily.","ec":"pwd            # print current folder\nls             # list files\ncd my-project  # enter a folder\ngit status     # a tool run from the shell","r":"Terminal = window. Shell = interpreter of commands.","g":["z_terminal","z_linux","z_interpreter","v_git","o_kubectl"],"fa":"The terminal is a text window where you type commands; the shell (Bash, Zsh, PowerShell) is the program that interprets them","cat":"ops"},{"id":"OPS-77","t":"m","l":0,"q":"What is Linux, and why does it matter for backend and cloud work?","o":["A free, open source OS family that runs most servers and containers","A programming language that is used to write web servers","A cloud provider that rents virtual machines by the hour","A Java framework that is used to build backend services"],"a":0,"e":"Linux is an operating system, like Windows or macOS. It is open source and runs on a very large share of servers and cloud virtual machines.\nDocker containers on a Linux machine share the host's Linux kernel, and most container images are based on Linux distributions such as Ubuntu, Debian or Alpine.\nSo you will often connect to Linux servers and use its terminal.","r":"Linux = the OS of most servers and containers.","g":["z_linux","container","n_os","z_backend","vm"],"fa":"A free, open source operating system family that runs most servers, containers and cloud machines","cat":"ops"},{"id":"OPS-78","t":"m","l":0,"q":"What is DevOps?","o":["A culture of practices that joins dev and ops to ship faster and safer","A job title for people who only fix printers and office networks","A programming language that was created for automation scripts","A type of database that is designed to store deployment logs"],"a":0,"e":"AWS describes DevOps as the combination of cultural philosophies, practices and tools that increases an organization's ability to deliver applications and services at high velocity.\nInstead of developers 'throwing code over the wall' to an operations team, one team owns building and running it.\nCommon practices: CI/CD, automated tests, infrastructure as code, monitoring.","r":"DevOps = build + run, automated and shared.","g":["z_devops","ci","cd","iac","z_monitoring","n_aws"],"fa":"A culture and set of practices that bring development and operations together so software is built, tested, released and run faster and more reliably","cat":"ops"},{"id":"OPS-79","t":"m","l":0,"q":"What problem does Docker solve?","o":["'It works on my machine' problems: the app runs the same everywhere","It makes the code compile faster on every machine of the team","It replaces the database with a lighter embedded one","It writes the tests of the application for the developers"],"a":0,"e":"Without Docker, an app depends on what is installed on each computer (Java version, libraries, settings). Differences cause errors.\nDocker packages the app and its dependencies into an image; running that image gives a container that behaves the same on your laptop, on a colleague's computer and on a server.\nContainers are lighter than virtual machines because they share the host's operating system kernel.","r":"Docker = package once, run the same everywhere.","g":["container","docker_image","vm","n_os","z_java"],"fa":"'It works on my machine' problems: it packages an app with everything it needs, so it runs the same everywhere","cat":"ops"},{"id":"OPS-80","t":"m","l":0,"q":"What is the difference between a Docker image and a container?","o":["The image is a read-only template; the container is a running instance","The image is a running program, and the container is just a file","They are the same thing, only named differently by each tool","The image is a database, and the container is a server"],"a":0,"e":"Think of the same relationship as class and object, or recipe and dish.\nYou build an image from a `Dockerfile` (the instructions). You run it with `docker run`, and each run creates a container. You can start many containers from one image.\nImages are stored in a registry such as Docker Hub.","ec":"docker build -t my-app .      # build an image\ndocker run -p 8080:8080 my-app  # start a container from it\ndocker ps                       # list running containers","r":"Image = template. Container = running instance.","g":["docker_image","container","dockerfile","o_registry","o_docker_cli"],"fa":"The image is the read-only template; the container is a running instance created from it","cat":"ops"},{"id":"OPS-81","t":"m","l":0,"q":"What is Kubernetes (also written K8s)?","o":["An open source system that automates deploying and scaling containers","A Docker command that builds and then runs a container locally","A Java library that is used to manage threads in a backend app","A cloud database that scales automatically across many machines"],"a":0,"e":"The Kubernetes documentation describes it as an open source system for automating deployment, scaling and management of containerized applications.\nDocker runs containers on one machine. When you have many containers on many machines, you need something to start them, restart them if they fail, scale them up and route traffic. That is Kubernetes.\n'K8s' is an abbreviation: K, then 8 letters, then s. It was originally designed by Google and is now maintained by the CNCF community.","r":"Kubernetes = orchestrator of containers.","g":["kubernetes","z_k8s_terms","container","o_docker_cli"],"fa":"An open source system that automates deploying, scaling and managing containerized applications across many machines","cat":"ops"},{"id":"OPS-82","t":"m","l":0,"q":"In Kubernetes, what are a cluster, a node and a Pod?","o":["Cluster: all machines. Node: one machine. Pod: smallest unit with containers","A cluster is a container; a node is a Pod; a Pod is a database","A node is a program; a Pod is an editor; a cluster is a file","They are three different names that all mean a container"],"a":0,"e":"- Cluster: a set of machines (nodes) that run your containerized applications; it has a control plane that manages it.\n- Node: a worker machine, physical or virtual.\n- Pod: the smallest deployable unit; it holds one or more containers that share network and storage.\nYou rarely create Pods directly: a Deployment keeps the desired number of Pods running.","r":"Cluster > nodes > Pods > containers.","g":["pod","kubernetes","z_k8s_terms","container","worker"],"fa":"A cluster is the whole set of machines; a node is one machine in it; a Pod is the smallest deployable unit and runs one or more containers","cat":"ops"},{"id":"OPS-83","t":"m","l":0,"q":"What is a cloud provider, and which are the three largest?","o":["A company that rents computing online: AWS, Azure and Google Cloud","A company that sells internet cables, like Oracle, IBM or Intel","A weather service that predicts storms, like AccuWeather","A type of antivirus program that runs on a remote server"],"a":0,"e":"Instead of buying and maintaining your own servers, you rent what you need and pay for what you use.\nAmazon Web Services (AWS), Microsoft Azure and Google Cloud Platform (GCP) are the three largest providers. Many jobs ask for AWS or Azure.\nThey offer similar services under different names, so learning one helps with the others.","r":"Cloud = rented computing. AWS, Azure, GCP.","g":["cloud","z_cloud_provider","n_aws","n_gcp","z_database"],"fa":"A company that rents computing resources over the internet (servers, storage, databases); the big three are AWS, Microsoft Azure and Google Cloud","cat":"ops"},{"id":"OPS-84","t":"m","l":0,"q":"What are the five essential characteristics of cloud computing according to NIST?","o":["On-demand self-service, network access, pooling, elasticity, measured service","Cheap, fast, small, secure and free, in that order of priority","Compile, test, build, deploy and monitor, in that exact order","Frontend, backend, database, cache and queue, as five layers"],"a":0,"e":"NIST (SP 800-145) defines cloud computing with five essential characteristics:\n1. On-demand self-service: you provision resources yourself without human contact.\n2. Broad network access: available over the network from many devices.\n3. Resource pooling: the provider's resources are shared among many customers.\n4. Rapid elasticity: resources grow and shrink quickly with demand.\n5. Measured service: usage is metered, so you pay for what you use.","r":"Self-service, network, pooling, elasticity, measured.","g":["cloud","z_nist_cloud","serverless","autoscaling","vm","z_cloud_provider"],"fa":"On-demand self-service, broad network access, resource pooling, rapid elasticity, measured service","cat":"ops"},{"id":"OPS-85","t":"m","l":0,"q":"What are IaaS, PaaS and SaaS?","o":["Cloud models: infrastructure (servers), platform (code), software (apps)","Three programming languages that are used to write cloud software","Three types of database that every cloud provider offers","Three Git commands that are used to publish code to the cloud"],"a":0,"e":"NIST's three service models:\n- IaaS (Infrastructure as a Service): you rent virtual machines, storage, networks and manage the OS and apps. Example: AWS EC2.\n- PaaS (Platform as a Service): you deploy your code and the provider manages the runtime and servers. Example: Azure App Service.\n- SaaS (Software as a Service): you just use the application. Example: Gmail.\nMore control means more responsibility.","r":"IaaS = machines. PaaS = platform. SaaS = app.","g":["o_iaas","cloud","vm","z_server","n_nist","o_ec2"],"fa":"Cloud service models: infrastructure (servers, networks), platform (a place to run your code) and software (a ready-made application)","cat":"ops"},{"id":"OPS-86","t":"m","l":0,"q":"What is a virtual machine (VM)?","o":["A simulated computer with its own OS that runs on a real machine","A faster CPU that is installed in the servers of a cloud provider","A Java keyword that is used to declare a virtual method","A type of browser that runs inside a data center of a company"],"a":0,"e":"A hypervisor divides one physical server into several isolated virtual computers. Each VM has its own operating system, CPU, memory and disk.\nCloud 'instances' such as AWS EC2 or Azure Virtual Machines are VMs.\nContainers are lighter: they share the host's operating system kernel instead of each carrying a full OS.","r":"VM = a full computer simulated in software.","g":["vm","container","n_os","n_cpu","o_ec2","n_aws"],"fa":"A software-simulated computer, with its own operating system, that runs on a physical machine","cat":"ops"},{"id":"OPS-87","t":"m","l":0,"q":"In AWS, what are a Region and an Availability Zone (AZ)?","o":["A Region is a geographic area; an AZ is an isolated data center in it","A Region is a server; an AZ is a database running on it","A Region is a country law; an AZ is a firewall rule","They are the same thing, named differently by each cloud"],"a":0,"e":"AWS describes a Region as a physical location in the world where it clusters data centers. Each Region has multiple, isolated Availability Zones (a minimum of three).\nRunning your app in more than one AZ keeps it available if one data center has a problem.\nAzure has the same ideas: regions and availability zones.","r":"Region = area. AZ = isolated data centers within it.","g":["z_region_az","cloud","availability_zone","n_aws","availability"],"fa":"A Region is a geographic area; an AZ is an isolated data center location inside it, and each Region has multiple (at least three) AZs","cat":"ops"},{"id":"OPS-88","t":"m","l":0,"q":"What is Amazon EC2?","o":["Elastic Compute Cloud: the AWS service to rent virtual servers","A managed database service that scales automatically on AWS","A browser-based code editor that is used for AWS projects","A Git hosting service that is run and managed by AWS"],"a":0,"e":"EC2 lets you launch virtual servers (instances) in minutes, choose CPU, memory and operating system, and pay for the time you use.\nYou can host a Java application directly on an EC2 instance, or run Docker/Kubernetes on top of it.\nAzure's equivalent is Azure Virtual Machines.","r":"EC2 = rent a virtual server in AWS.","g":["o_ec2","vm","n_aws","n_os","z_server","kubernetes"],"fa":"Elastic Compute Cloud: AWS's service for renting virtual servers in the cloud","cat":"ops"},{"id":"OPS-89","t":"m","l":0,"q":"What are Amazon S3 and Azure Blob Storage?","o":["Cloud object storage for files such as images, backups and logs","Managed relational databases that are queried with SQL","Container orchestrators that schedule workloads on nodes","CI servers that build and test the code of a project"],"a":0,"e":"Object storage keeps files (objects) in containers called buckets (S3) or containers (Azure Blob), each reachable by a key or URL.\nAmazon S3 = Simple Storage Service. Typical uses: images and videos for an app, backups, data lakes, static websites.\nIt is not a database: you do not query it with SQL, you store and retrieve whole files.","r":"S3 / Blob = cloud storage for files.","g":["z_object_storage","cloud","s3","container","object","sql"],"fa":"Cloud object storage services for files such as images, backups and logs","cat":"ops"},{"id":"OPS-90","t":"m","l":0,"q":"What is Microsoft Entra ID?","o":["Microsoft's cloud identity and access service, formerly Azure AD","A Microsoft relational database that is built for cloud applications","A programming language created for writing Azure functions","A Docker registry that is run and managed by Microsoft"],"a":0,"e":"Microsoft renamed Azure Active Directory to Microsoft Entra ID in 2023. Same product, new name, so older job descriptions still say Azure AD.\nIt manages who you are (sign in, single sign-on, MFA) and what you can access in Azure, Microsoft 365 and other apps.\nIdentity services answer two questions: authentication (who are you) and authorization (what can you do).","r":"Entra ID = Azure AD, renamed.","g":["z_entra","mfa","access_control","authn","identity","authz"],"fa":"Microsoft's cloud identity and access management service, formerly called Azure Active Directory (Azure AD)","cat":"ops"},{"id":"OPS-91","t":"m","l":0,"q":"What is Infrastructure as Code (IaC)?","o":["Managing infrastructure with code files instead of manual clicks","Writing application code directly on a production server","A Java coding style that uses infrastructure classes","Storing the source code of a project in the cloud"],"a":0,"e":"With IaC, you describe the infrastructure you want in text files that are stored in Git, reviewed and applied by a tool.\nBenefits: repeatable (the same file builds the same environment), versioned and less prone to manual mistakes.\nCommon tools: Terraform, AWS CloudFormation, Azure Bicep.","r":"IaC = infrastructure defined in code.","g":["iac","terraform","z_server","v_git","n_aws"],"fa":"Managing servers, networks and other infrastructure through code files instead of manual clicks, for example with Terraform","cat":"ops"},{"id":"OPS-92","t":"m","l":0,"q":"What are logs and monitoring?","o":["Logs record events your app writes; monitoring tracks metrics and alerts","Logs are passwords, and monitoring is the encryption of data","Logs are tests, and monitoring is the compiler of the code","They are the same thing, only named by different teams"],"a":0,"e":"When something fails in production you can't attach a debugger, so you read the logs: timestamps, severity levels (INFO, WARN, ERROR) and messages.\nMonitoring tracks numbers over time (response time, error rate, CPU) and sends alerts when they go beyond a threshold.\nIn containers the convention is to write logs to the standard output; for example `docker logs <container>` or `kubectl logs <pod>` shows them.","r":"Logs = what happened. Monitoring = is it healthy now?","g":["logs","z_monitoring","o_kubectl","o_docker_cli","container","pod"],"fa":"Logs are a record of events your app writes; monitoring is watching metrics and alerts to know whether the system is healthy","cat":"ops"},{"id":"OPS-93","t":"m","l":0,"q":"What do CI and CD stand for?","o":["Continuous Integration and Continuous Delivery (or Deployment)","Code Inspection and Code Debugging, done by reviewers","Cloud Instance and Cloud Database, the two basic services","Compile Immediately and Copy Data, two build commands"],"a":0,"e":"- Continuous Integration: every time someone pushes code, a server builds it and runs the tests automatically, so errors are found quickly.\n- Continuous Delivery: the tested build is always ready to be released. Continuous Deployment goes one step further and releases it to production automatically.\nTools: GitHub Actions, GitLab CI, Jenkins, Azure DevOps.","r":"CI = build+test on every push. CD = ready/auto release.","g":["ci","cd","o_cicd_tools","z_devops","z_server"],"cat":"ops"},{"id":"OPS-94","t":"f","l":0,"q":"Explain Docker, Kubernetes and the cloud to a friend with no technical background.","a":"- Docker: a box that holds an app and everything it needs, so it works the same on any computer.\n- Kubernetes: the manager of many boxes; it starts them, replaces broken ones and adds more when there is more demand.\n- Cloud (AWS, Azure): instead of buying servers, you rent computers and storage over the internet and pay for what you use.\n- Together: you put your app in a Docker box, and Kubernetes runs many boxes on rented cloud machines.","g":["container","kubernetes","cloud","n_aws","z_server"],"cat":"ops"},{"id":"OPS-95","t":"f","l":0,"q":"What is the difference between a virtual machine and a container?","a":"- A VM simulates a full computer with its own operating system. It is heavier and slower to start.\n- A container packages only the app and its dependencies, and shares the host's operating system kernel. It is lighter and starts quickly.\n- Use VMs for strong isolation or different operating systems; use containers to ship and scale apps consistently.\n- They are often combined: containers running inside cloud VMs.","g":["vm","container","docker_image","kubernetes","z_linux","dockerfile","n_os"],"cat":"ops"},{"id":"VCS-01","t":"m","l":1,"q":"What is Maven used for in a Java project?","o":["Only to run the program once it has been built","Building the project and managing its dependencies","Writing the documentation for the whole project","Editing the source code files of the project"],"a":1,"e":"Maven is a build tool. You describe the project in one file, `pom.xml` (Project Object Model): its name and version, the libraries it needs (dependencies) and the plugins to use.\nWith one command (`mvn package`) Maven downloads the libraries, compiles the code, runs the tests and creates the JAR or WAR.\nIt follows \"convention over configuration\": source in `src/main/java`, tests in `src/test/java`, output in `target/`. Gradle is a popular alternative.","r":"Maven = pom.xml describes the project; commands build it.","g":["v_maven","v_pom","z_java","n_maven_layout","n_mvn_cmds","z_jar"],"fa":"Building the project (compile, test, package) and managing dependencies, driven by a `pom.xml` file","cat":"vcs"},{"id":"VCS-02","t":"m","l":1,"q":"What do the Maven coordinates `groupId`, `artifactId` and `version` identify?","o":["The postal address and contact data of the author","A unique artifact: its group, its name and its version","The server where the project runs in production","The results of the tests of the project's build"],"a":1,"e":"Every Maven artifact is identified by GAV: Group, Artifact, Version.\nExample: `org.springframework.boot : spring-boot-starter-web : 3.3.0`.\n- `groupId`: usually the reverse domain of the organization (`com.acme`).\n- `artifactId`: the name of the library or project.\n- `version`: the release (`1.4.2`, or `1.5.0-SNAPSHOT` for work in progress).\nWith these three Maven finds the right file in a repository.","ec":"<dependency>\n  <groupId>com.fasterxml.jackson.core</groupId>\n  <artifactId>jackson-databind</artifactId>\n  <version>2.17.1</version>\n</dependency>","r":"GAV = group + artifact + version.","g":["v_gav","v_pom","v_maven","sp_jackson","z_library","sp_starter"],"fa":"A unique artifact (library or project): who publishes it (group), its name, and which version","cat":"vcs"},{"id":"VCS-03","t":"m","l":1,"q":"Which is the correct order of the main Maven default lifecycle phases?","o":["package, compile, test, install, verify, deploy","validate, compile, test, package, verify, install","compile, deploy, test, package, install, validate","test, compile, install, clean, package, validate"],"a":1,"e":"Maven's default lifecycle runs phases in order, and running a phase also runs all previous ones:\n1. validate: check the project is correct.\n2. compile: compile `src/main/java`.\n3. test: run unit tests.\n4. package: create the JAR/WAR.\n5. verify: run integration checks.\n6. install: copy the artifact to your local repository (`~/.m2`).\n7. deploy: upload it to a remote repository.\n`clean` belongs to a separate lifecycle: it deletes `target/`.","r":"validate, compile, test, package, verify, install, deploy.","g":["v_maven_lifecycle","v_maven","v_remote","n_maven_layout","z_deploy","unit_test"],"fa":"validate, compile, test, package, verify, install, deploy","cat":"vcs"},{"id":"VCS-04","t":"m","l":1,"q":"What is the difference between `mvn package` and `mvn install`?","o":["There is no difference between them in Maven builds","`package` makes the JAR; `install` also copies it to ~/.m2","`install` deletes the JAR from `target/` after building","`package` uploads the JAR to the internet repository"],"a":1,"e":"Both compile, test and package. `mvn package` stops after creating the JAR/WAR in the `target/` folder.\n`mvn install` goes further and copies the artifact into the local repository (`~/.m2/repository`), so other projects on your machine can use it as a dependency.\n`mvn deploy` goes even further and uploads to a shared remote repository (Nexus, Artifactory) for your team.\nA common daily command is `mvn clean install`.","ec":"mvn clean install          # delete target/, build, test, install locally\nmvn clean package -DskipTests   # build without running tests","r":"package = JAR in target. install = + local repo. deploy = + remote repo.","g":["v_maven_lifecycle","v_local_repo","z_jar","n_maven_layout","n_mvn_cmds","v_maven"],"fa":"`package` builds the JAR in `target/`; `install` also copies it into your local Maven repository (`~/.m2`) so other local projects can depend on it","cat":"vcs"},{"id":"VCS-05","t":"m","l":2,"q":"What do the Maven dependency scopes `compile`, `provided`, `runtime` and `test` mean?","o":["They are the names of branches used in a Git repository","Build and run, build only, run only, and tests only","They define the author and license of each library","They are the version numbers of a Maven release"],"a":1,"e":"The scope controls when a dependency is on the classpath:\n- `compile` (default): always, and it is packaged.\n- `provided`: available at compile time but not packaged, because the server provides it (e.g. the Servlet API in an external Tomcat).\n- `runtime`: not needed to compile, needed at execution (e.g. a JDBC driver).\n- `test`: only when compiling and running tests (JUnit, Mockito).","ec":"<dependency>\n  <groupId>org.junit.jupiter</groupId>\n  <artifactId>junit-jupiter</artifactId>\n  <version>5.10.2</version>\n  <scope>test</scope>\n</dependency>","r":"test = tests only; provided = server gives it; runtime = needed only to run.","g":["v_dep_scope","v_pom","v_maven","sp_jdbc","api"],"fa":"`compile`: needed to build and run; `provided`: needed to build but supplied by the runtime; `runtime`: not needed to compile but needed to run; `test`: only for tests","cat":"vcs"},{"id":"VCS-06","t":"m","l":2,"q":"What is a transitive dependency?","o":["A dependency that changes very often between releases","A library you did not declare, pulled in by another one","A dependency that is only used while running the tests","A library written in another programming language"],"a":1,"e":"If your project depends on library A, and A depends on B, Maven also downloads B for you: B is a transitive dependency.\nIt is convenient, but it can cause version conflicts when two libraries need different versions of C. Maven resolves it with \"nearest definition wins\": the version closest to your project in the dependency tree.\nInspect the tree with `mvn dependency:tree`; exclude or pin versions with `<exclusions>` or `dependencyManagement`.","ec":"mvn dependency:tree","r":"Transitive = dependencies of your dependencies.","g":["v_transitive","v_pom","v_dep_scope","v_gav","v_bom","dependency"],"fa":"A library you did not declare, pulled in because one of your dependencies needs it","cat":"vcs"},{"id":"VCS-07","t":"m","l":2,"q":"What is a `-SNAPSHOT` version in Maven?","o":["A stable release that never changes after publishing","A development version that can change over time","A version that cannot be built with Maven or Gradle","A backup copy of the release kept in a repository"],"a":1,"e":"A version such as `1.2.0-SNAPSHOT` means \"work in progress toward 1.2.0\". The artifact with that same version can be replaced many times.\nA release version like `1.2.0` should never change once published: anyone who depends on it gets exactly the same bytes.\nGood practice: never depend on SNAPSHOTs in production builds, because the build is not reproducible.","r":"SNAPSHOT = mutable work in progress; release = fixed forever.","g":["v_snapshot","semver","v_maven","immutable","mutable"],"fa":"A development version that can change; Maven may re-download it as it is updated, unlike an immutable release","cat":"vcs"},{"id":"VCS-08","t":"m","l":2,"q":"What do `<parent>` and `<dependencyManagement>` (BOM) help with in a pom?","o":["Naming the project and listing all of its modules","Centralizing versions so modules stay consistent","Running the tests faster using parallel threads","Publishing the project to Git on every build"],"a":1,"e":"`<parent>`: your pom inherits configuration from another pom. `spring-boot-starter-parent` sets plugin defaults and dependency versions.\n`<dependencyManagement>`: lists versions in one place. Children and dependencies then omit `<version>`. A BOM (Bill of Materials) is a pom that only does this, such as `spring-boot-dependencies`; you import it and get a tested set of compatible versions.\nBenefits: fewer conflicts, one place to upgrade, multi-module projects stay aligned.","ec":"<parent>\n  <groupId>org.springframework.boot</groupId>\n  <artifactId>spring-boot-starter-parent</artifactId>\n  <version>3.3.0</version>\n</parent>","r":"Parent pom or BOM = one place that decides versions.","g":["v_bom","v_pom","v_gav","v_transitive","v_dep_scope","semver"],"fa":"Centralizing versions so many dependencies and modules stay consistent without repeating version numbers","cat":"vcs"},{"id":"VCS-09","t":"m","l":2,"q":"What is the difference between Maven Surefire and Failsafe plugins?","o":["They are the same plugin under two different names","Surefire runs unit tests (`*Test`); Failsafe runs `*IT`","Surefire builds Docker images for the application","Failsafe only works on Windows machines and servers"],"a":1,"e":"Plugins do the real work in each Maven phase.\n- maven-surefire-plugin: runs unit tests during `test` (classes named `*Test`).\n- maven-failsafe-plugin: runs integration tests (classes named `*IT`) during `integration-test`, and checks results in `verify`. This separation lets Maven shut down external things (like a test server) before reporting failure.\nThis split keeps `mvn test` fast.","r":"Surefire = unit tests. Failsafe = integration tests.","g":["v_maven_lifecycle","unit_test","integration_test","v_maven","n_mvn_cmds"],"fa":"Surefire runs unit tests in the `test` phase (`*Test`); Failsafe runs integration tests in `integration-test`/`verify` (`*IT`) so a failure does not leave resources half-cleaned","cat":"vcs"},{"id":"VCS-10","t":"m","l":1,"q":"What is the difference between Git and GitHub?","o":["They are the same product with two different names","Git is the version control tool; GitHub hosts repos","GitHub is a text editor that is made for coding","Git only works when it is used together with GitHub"],"a":1,"e":"Git is a distributed version control system: it records the history of your files so you can see changes, go back, and work on parallel versions (branches). It runs locally and needs no internet.\nGitHub (also GitLab, Bitbucket, Azure DevOps) is a service that stores a shared copy of the repository and adds collaboration: pull requests, code review, issues and automated pipelines.","r":"Git = tool. GitHub = hosting platform for Git repos.","g":["v_git","v_remote","v_pull_request","ci","z_code_review","z_devops"],"fa":"Git is the version control tool on your computer; GitHub is a website that hosts Git repositories and adds pull requests, issues and CI","cat":"vcs"},{"id":"VCS-11","t":"m","l":1,"q":"Git has three main areas on your machine. Which list is correct?","o":["Working directory, staging area, local repository","Server, client, cache, and the remote repository","Branch, tag, commit, and the local configuration","Backup, restore, delete, and the history logs"],"a":0,"e":"1. Working directory: the files you see and edit.\n2. Staging area (index): a waiting room where you choose what goes into the next commit (`git add`).\n3. Local repository: the permanent history of commits (`git commit`).\nThen `git push` sends your commits to a remote repository (GitHub).\nFlow: edit, `git add`, `git commit`, `git push`.","ec":"git add src/App.java\ngit commit -m \"Add user validation\"\ngit push origin feature/validation","r":"Edit, add (stage), commit, push.","g":["v_git","git_commit","v_staging","n_git_cmds","v_remote","z_java"],"fa":"Working directory, staging area (index), local repository","cat":"vcs"},{"id":"VCS-12","t":"m","l":1,"q":"What is the difference between `git fetch` and `git pull`?","o":["There is no difference, they do the same thing","`fetch` downloads only; `pull` is fetch plus merge","`pull` uploads your changes; `fetch` deletes them","`fetch` only works for tags, not for branches"],"a":1,"e":"`git fetch` updates your knowledge of the remote (new commits and branches) but does not touch your working files. It is safe: you can inspect first (`git log origin/main`).\n`git pull` does `fetch` and then merges (or rebases, with `--rebase`) those changes into your current branch immediately. It may cause conflicts you must resolve.\nMany people use `git pull --rebase` to keep a linear history.","r":"pull = fetch + merge.","g":["v_remote","merge","rebase","v_git","n_git_cmds","n_fetch"],"fa":"`fetch` downloads remote changes without changing your files; `pull` = fetch + merge into your current branch","cat":"vcs"},{"id":"VCS-13","t":"m","l":2,"q":"What is the difference between `git reset` and `git revert` for undoing a commit?","o":["They are identical in the effect they have on history","`reset` rewrites history; `revert` adds an undoing commit","`revert` deletes the whole repository from the disk","`reset` only works on remote branches, never local"],"a":1,"e":"`git reset --hard <commit>` moves your branch pointer back and discards later commits and changes. Fine for local work, but if others already have those commits, you create a mess (it rewrites history).\n`git revert <commit>` adds a new commit with the opposite changes. History stays intact, so it is the safe way to undo something already pushed to a shared branch like `main`.","ec":"git revert 3f2a9c1        # safe on shared branches\ngit reset --hard HEAD~1   # local only: drops last commit and changes","r":"Shared branch: revert. Local mess: reset.","g":["v_reset_revert","git_commit","v_reflog","rebase","merge","v_git"],"fa":"`reset` moves the branch back, rewriting history (risky if already pushed); `revert` creates a NEW commit that undoes the old one, safe for shared branches","cat":"vcs"},{"id":"VCS-14","t":"m","l":2,"q":"What does `git stash` do?","o":["Deletes uncommitted changes forever, with no way back","Saves uncommitted changes on a stack; `stash pop` restores","Pushes the uncommitted changes to the remote branch","Creates a tag on the current commit of the branch"],"a":1,"e":"You are halfway through a change and need to switch branch to fix something urgent. You do not want to commit unfinished work.\n`git stash` stores your changes in a temporary shelf and gives you a clean directory. Later `git stash pop` reapplies them (and removes them from the shelf); `git stash list` shows the stack.","r":"stash = shelf for unfinished work.","g":["v_stash","v_staging","git_branch","v_merge_conflict","v_remote","v_git"],"fa":"Temporarily saves your uncommitted changes on a stack and cleans the working directory, so you can switch tasks; `git stash pop` brings them back","cat":"vcs"},{"id":"VCS-15","t":"m","l":2,"q":"What does `git cherry-pick <commit>` do?","o":["Deletes a commit from the history of the branch","Applies one commit from another branch onto yours","Merges the entire other branch into your branch","Renames the current branch in the local repository"],"a":1,"e":"Sometimes you want just ONE commit from another branch, for example a bug fix made on `develop` that must also go to `release/1.2`.\n`git cherry-pick <hash>` copies that commit's changes onto your current branch, creating a new commit with a different hash.\nUse it sparingly: duplicated commits can confuse history later.","r":"cherry-pick = copy one commit to here.","g":["v_cherry_pick","git_commit","git_branch","merge","v_merge_conflict","rebase"],"fa":"Applies the changes of one specific commit from another branch onto your current branch as a new commit","cat":"vcs"},{"id":"VCS-16","t":"m","l":2,"q":"What is a typical difference between Git Flow and trunk-based development?","o":["Git Flow has long-lived branches; trunk-based, short ones","There is no difference between the two in practice","Trunk-based has no branches and also no code review","Git Flow requires no merges at all in the workflow"],"a":0,"e":"Git Flow: `main` (releases), `develop` (integration), plus feature, release and hotfix branches. Good for scheduled, versioned releases; heavier process and bigger merges.\nTrunk-based development: everyone integrates into `main` very often (at least daily), with small short-lived branches or direct commits, protected by automated tests and feature flags for unfinished work. It fits continuous delivery.\nMany teams use a lighter hybrid: feature branch, pull request, merge to main.","r":"Git Flow = many long branches. Trunk-based = small, frequent merges to main.","g":["v_branching_strategy","feature_flag","ci","v_git","cd","v_pull_request"],"fa":"Git Flow uses many long-lived branches (develop, release, hotfix); trunk-based uses short-lived branches merged to `main` frequently, supported by feature flags and CI","cat":"vcs"},{"id":"VCS-17","t":"m","l":1,"q":"What is a pull request (PR) / merge request?","o":["A request to download Git onto your own machine","A proposal to merge your branch, with review and CI","A backup of the database made before a release","A way to delete a branch from the remote server"],"a":1,"e":"After working in your branch, you open a pull request on GitHub/GitLab. It shows the diff, allows comments and approvals (code review), and runs automated checks (build, tests, lint).\nOnly when reviewers approve and checks pass is the branch merged. This catches bugs early, spreads knowledge and keeps `main` healthy.\nGood PRs are small, have a clear description and link to the ticket.","r":"PR = review + checks before merging.","g":["v_pull_request","ci","git_branch","z_code_review"],"fa":"A proposal to merge your branch into another, where teammates review the code and CI runs before it is accepted","cat":"vcs"},{"id":"VCS-18","t":"m","l":1,"q":"What is the purpose of a `.gitignore` file?","o":["To store the access passwords of the repository","To list files Git must not track, like build output","To delete files from the repository automatically","To rename the branches of the repository in bulk"],"a":1,"e":"Some files should never be in the repository: compiled output (`target/`, `node_modules/`), IDE folders (`.idea/`), logs, and above all secrets such as `.env` files with passwords.\nList patterns in `.gitignore` and Git will not stage them. Note: it does not remove files already tracked; use `git rm --cached file` for those.\nIf a secret was committed, treat it as leaked: rotate it, since history keeps it.","ec":"target/\n.idea/\n*.log\n.env","r":".gitignore keeps build output and secrets out of the repo.","g":["v_gitignore","n_maven_layout","v_git","z_ide","secret"],"fa":"To list files and folders Git should not track (build output like `target/`, IDE settings, secrets, logs)","cat":"vcs"},{"id":"VCS-19","t":"m","l":3,"q":"You ran `git reset --hard` by mistake and \"lost\" commits. What can save you?","o":["Nothing; the commits are gone forever after a reset","`git reflog` shows where HEAD was, so you can restore it","Reinstalling Git on the machine you are working on","Deleting the .git folder and cloning the repo again"],"a":1,"e":"Git rarely deletes commits immediately. `git reflog` is a local log of every position HEAD has been in (commits, resets, checkouts, rebases).\nFind the hash from before the mistake (`HEAD@{3}`) and restore it: `git reset --hard <hash>` or create a branch there: `git branch rescue <hash>`.\nUnreferenced commits are kept for roughly 30 to 90 days before garbage collection. Uncommitted changes lost by a hard reset, however, cannot be recovered this way.","ec":"git reflog\ngit branch rescue HEAD@{2}","r":"reflog = Git's undo history for HEAD.","g":["v_reflog","git_branch","v_remote","merge","v_git","rebase"],"fa":"`git reflog` shows where HEAD used to point, so you can find the commit hash and restore it with `git reset` or `git checkout`","cat":"vcs"},{"id":"VCS-20","t":"m","l":1,"q":"What are the main phases of the Software Development Life Cycle (SDLC)?","o":["Only coding, because the rest is not part of it","Requirements, design, build, test, deploy, maintain","Marketing, sales, support, and customer success","Compile, link, run, and then package the output"],"a":1,"e":"SDLC describes how software goes from idea to production and beyond:\n1. Requirements: what must it do and why.\n2. Design: architecture, data model, APIs.\n3. Implementation: writing code.\n4. Testing: unit, integration, acceptance.\n5. Deployment: release to users.\n6. Maintenance: monitor, fix bugs, improve.\nWaterfall does these in strict order; Agile repeats them in short cycles (sprints) with frequent feedback. CI/CD automates testing and deployment.","r":"Requirements, design, code, test, deploy, maintain (repeat).","g":["v_sdlc","ci","cd","b_sprint","z_deploy","b_agile"],"fa":"Requirements, design, implementation, testing, deployment, maintenance","cat":"vcs"},{"id":"VCS-21","t":"m","l":2,"q":"What is a good commit message and commit size?","o":["'fix' as the message, and one huge commit per week","A short imperative summary, in a small focused commit","The full source code of the changed file as text","Only emojis as the message, with no further text"],"a":1,"e":"Small, focused commits make history readable, reviews easier, `git bisect` possible and reverts safe.\nSubject line: imperative mood, about 50 characters (\"Add retry to payment client\"). Optional body explaining why. Reference the ticket (`PROJ-123`).\nAvoid: \"fix\", \"stuff\", \"WIP\", and mixing refactoring with feature changes in one commit.","r":"One logical change per commit; explain the why.","g":["git_commit","refactoring","v_git","n_wip"],"fa":"A short, imperative summary of WHAT and WHY (\"Fix null email in signup\"), in a small commit that does one logical change","cat":"vcs"},{"id":"VCS-22","t":"f","l":1,"q":"Explain the basic Git workflow you use every day with a team.","a":"- `git switch -c feature/x` (create a branch from an updated `main`).\n- Edit, then `git add` and `git commit` small logical commits.\n- `git fetch` / `git pull --rebase` to stay up to date with `main`.\n- `git push -u origin feature/x`, open a pull request.\n- Code review and CI checks; fix feedback with new commits.\n- Merge (squash or merge commit, per team rule), delete the branch.\n- Resolve conflicts by editing, `git add`, continue; never force-push shared branches.","g":["v_git","n_git_cmds","v_pull_request","z_code_review","rebase","n_fetch","ci"],"cat":"vcs"},{"id":"VCS-23","t":"f","l":2,"q":"Describe the Maven build lifecycle and how you would fix a dependency conflict.","a":"- Lifecycle: validate, compile, test, package, verify, install, deploy; `clean` removes `target/`.\n- Dependencies are resolved from Maven Central or a company repository (Nexus/Artifactory) into `~/.m2`.\n- Conflict symptoms: `NoSuchMethodError`, `ClassNotFoundException`, two versions of the same library.\n- Diagnose with `mvn dependency:tree` (add `-Dverbose`).\n- Fix: pin the version in `dependencyManagement`, add `<exclusions>` for the unwanted transitive version, or import a BOM.\n- Prevent: use `maven-enforcer-plugin` (dependencyConvergence), avoid SNAPSHOTs in releases.","g":["v_maven","n_maven_layout","v_local_repo","v_bom"],"cat":"vcs"},{"id":"VCS-24","t":"f","l":2,"q":"Explain Agile and Scrum to someone who has never worked in a team.","a":"- Agile: build software in small increments, get feedback early, adapt to change; values working software, collaboration and responding to change over rigid plans.\n- Scrum is a framework: work in fixed sprints (1 to 4 weeks).\n- Roles: Product Owner (decides priorities), Scrum Master (helps the process), Developers.\n- Artifacts: product backlog (all wanted work), sprint backlog (chosen for this sprint), increment (working result).\n- Events: sprint planning, daily stand-up (15 min), sprint review (demo), retrospective (how to improve).\n- Kanban alternative: visual board, limit work in progress, continuous flow.","g":["b_scrum","b_sprint","b_agile","b_retro","b_kanban"],"cat":"vcs"},{"id":"VCS-25","t":"m","l":0,"q":"What is version control and why do teams use it?","o":["A system that records every change, to compare and undo","Naming the files v1, v2, v3 by hand in a folder","A backup tool that overwrites the previous copy","A code formatter that makes the style consistent"],"a":0,"e":"Without version control, people email zip files or end with 'final_v3_REAL.docx'.\nWith it, every change is recorded with who made it, when and why, and you can go back to any point in history.\nSeveral people can work in parallel and then combine their work (merge).\nGit is the most used tool for this.","r":"Version control = history + collaboration for code.","g":["v_git","git_commit","git_branch","merge","v_remote","v_pull_request","v_branching_strategy"],"fa":"A system that records every change to files over time, so you can compare versions, undo mistakes and work together without overwriting each other","cat":"vcs"},{"id":"VCS-26","t":"m","l":0,"q":"What is Git?","o":["A distributed version control system with full history","A website that hosts the code of many projects","A programming language used for scripting builds","A project management app with boards and tickets"],"a":0,"e":"Git was developed in 2005 by the Linux kernel community, led by Linus Torvalds, with goals such as speed, a simple design and strong support for many parallel branches.\n'Distributed' means that you have the entire history on your own machine and can work offline.\nGitHub, GitLab and Bitbucket are services that host Git repositories and add collaboration features. Git and GitHub are not the same thing.","r":"Git = the tool. GitHub = a service that hosts Git repos.","g":["v_git","v_remote","git_commit","git_branch","v_staging","v_pull_request","v_gitignore"],"fa":"A distributed version control system: every developer has a full copy of the project and its history","cat":"vcs"},{"id":"VCS-27","t":"m","l":0,"q":"What is a Git repository (repo)?","o":["The project folder tracked by Git, with its history","A single commit that was saved in the history","A cloud server that stores the code of a company","A text editor that is used to write the code"],"a":0,"e":"GitHub's docs: a repository, or Git project, encompasses the entire collection of files and folders associated with a project, along with each file's revision history.\nYou get one by running `git init` in a folder, or by copying an existing one with `git clone <url>`.\nThe local repository and the remote one (for example on GitHub) are separate copies that you synchronize.","r":"Repo = project + its full history.","g":["v_git","v_remote","git_commit","git_branch","v_gitignore","merge"],"fa":"The project folder tracked by Git, with all its files and their history","cat":"vcs"},{"id":"VCS-28","t":"m","l":0,"q":"What is a Git commit?","o":["A snapshot of your staged changes, with a message","Deleting a file from the project working directory","Sending the code to the production environment","A branch that is created from the current commit"],"a":0,"e":"The file history appears as snapshots in time called commits.\nYou choose what goes in the snapshot with `git add`, then save it with `git commit -m \"Fix login error\"`. Each commit has an ID, an author, a date and a message.\nGood commits are small and have clear messages in the imperative: 'Add', 'Fix', 'Remove'.","r":"Commit = a snapshot with a message.","g":["git_commit","v_staging","git_branch","v_remote","v_reflog","v_git"],"fa":"A saved snapshot of your staged changes in the project history, with a message describing it","cat":"vcs"},{"id":"VCS-29","t":"m","l":0,"q":"What is a Git branch?","o":["A separate line of development, apart from `main`","A copy of the project hosted on another website","A type of commit message with a special format","A file that was deleted from the working directory"],"a":0,"e":"Commits can be organized into multiple lines of development called branches.\nThe usual way to work: create a branch for your feature (`git switch -c feature/login`), commit there, and when it is ready open a pull request to merge it into the main branch.\nThe main line is often called `main`. Branches are cheap in Git, so use them freely.","r":"Branch = a safe parallel line of work.","g":["git_branch","merge","v_git","v_pull_request","git_commit"],"fa":"A separate line of development where you can work without affecting the main line","cat":"vcs"},{"id":"VCS-30","t":"m","l":0,"q":"Which sequence is the everyday Git flow to save and share a change?","o":["`git add` → `git commit` → `git push`","`git push` → `git add` → `git commit`","`git commit` → `git clone` → `git add`","`git pull` → `git delete`"],"a":0,"e":"- `git clone <url>`: copy a remote repo to your machine (once).\n- `git add <file>`: choose changes for the next snapshot (staging).\n- `git commit -m \"message\"`: save the snapshot locally.\n- `git push`: send your commits to the remote repository.\n- `git pull`: bring the others' commits to your machine.\nBefore starting work, pull; when done, add, commit and push.","r":"add → commit → push.","g":["git_commit","v_remote","v_git","n_git_cmds","repository"],"cat":"vcs"},{"id":"VCS-31","t":"m","l":0,"q":"What is `pom.xml` in a Maven project?","o":["The Project Object Model: dependencies and builds","The main Java class that starts the application","The database script that creates all the tables","A test report that is created after the build"],"a":0,"e":"Maven's guide: the pom.xml file is the core of a project's configuration in Maven, a single file with most of the information needed to build the project.\nInside you find the project's coordinates (`groupId`, `artifactId`, `version`), the Java version, and the list of dependencies that Maven downloads for you.\nMaven is a build tool, so you describe what you want and it runs the steps.","r":"pom.xml = the project's configuration for Maven.","g":["v_pom","v_gav","v_maven","z_java","object"],"fa":"The project's Project Object Model: the main configuration file with its coordinates, dependencies and build settings","cat":"vcs"},{"id":"VCS-32","t":"m","l":0,"q":"In a standard Maven project, where do the source code and the test code go?","o":["`src/main/java` and `src/test/java`","`bin/main` and `lib/test` folders","`target/src` and `docs/test` folders","`web/java` and `test/java` folders"],"a":0,"e":"Maven uses a standard folder layout, so every project looks alike:\n- `src/main/java`: your application code.\n- `src/test/java`: your tests.\n- `src/main/resources`: configuration files such as application.properties.\n- `target`: output of the build, like the packaged JAR. You do not edit it and you do not commit it.","r":"main code in src/main/java, tests in src/test/java.","g":["v_maven","z_jar","z_java","n_maven_layout","n_app_props"],"cat":"vcs"},{"id":"VCS-33","t":"m","l":0,"q":"What does `mvn clean` do?","o":["Removes the output of the previous build (`target`)","Deletes your source code from the project folder","Downloads all the dependencies again from the web","Runs the tests of the project in a clean state"],"a":0,"e":"Maven has several lifecycles. The `clean` lifecycle removes everything the previous build produced.\nA typical command is `mvn clean package`: clean first, then compile, test and package, so old leftovers cannot cause strange results.\nFor a normal build, the phases run in order: validate, compile, test, package, verify, install, deploy.","r":"clean = delete previous build output.","g":["v_maven_lifecycle","v_maven","n_mvn_cmds","z_deploy"],"fa":"Removes files generated by the previous build (the `target` folder)","cat":"vcs"},{"id":"VCS-34","t":"m","l":0,"q":"What is a 'build' in software?","o":["The automated steps that turn source into a runnable app","Constructing a server room for the engineering team","Writing the very first version of the code of an app","Drawing the UI of an application in a design tool"],"a":0,"e":"Source code cannot always be run as it is. A build compiles it, downloads dependencies, runs tests and packages the result (for example a JAR or a Docker image).\nBuild tools: Maven and Gradle (Java), npm scripts (JavaScript), pip with setuptools or Poetry (Python).\nA CI server runs the build on every push, so the team knows right away if it breaks.","r":"Build = source code → tested, packaged artifact.","g":["v_maven","ci","docker_image","javascript","z_java","z_pip"],"fa":"The automated process that turns source code into something that can run or be shipped: compile, run tests, package","cat":"vcs"},{"id":"VCS-35","t":"f","l":0,"q":"Explain Git and GitHub to a beginner.","a":"- Git is a tool on your computer that records the history of your project as commits (snapshots).\n- It lets you create branches to try changes safely and merge them later.\n- GitHub is a website (also GitLab, Bitbucket) that stores a copy of your Git repository online so teams can share it.\n- On top of Git, GitHub adds pull requests, code review, issues and automation (Actions).\n- Daily flow: clone, create a branch, edit, add, commit, push, open a pull request.","g":["v_git","git_commit","git_branch","v_pull_request","z_code_review"],"cat":"vcs"},{"id":"TST-01","t":"m","l":2,"q":"What is a pytest fixture?","o":["A decorator that makes a test skip itself","A reusable function giving setup and teardown","A test that always passes by its own design","A flag to run the whole test suite in parallel"],"a":1,"e":"Many tests need the same preparation: a test user, a database session, a temporary folder. A fixture is a function marked with `@pytest.fixture` that prepares it.\nA test simply lists the fixture's name as a parameter and pytest passes in the result.\nCode after `yield` is cleanup that runs after the test, even if it failed. `scope` controls reuse (per test, module or whole session).","ec":"@pytest.fixture\ndef db():\n    conn = make_test_db()\n    yield conn          # the test runs here\n    conn.close()        # cleanup\n\ndef test_create_user(db):\n    ...","r":"Fixture = reusable setup injected by parameter name.","g":["fixture","pytest","conftest","parametrize","test_isolation","n_yield"],"fa":"A reusable function that provides setup (and teardown via `yield`) to tests that request it by parameter name","cat":"test"},{"id":"TST-02","t":"m","l":1,"q":"How many test cases does pytest run here?","c":"import pytest\n\n@pytest.mark.parametrize(\"a,b,expected\", [\n    (1, 2, 3),\n    (0, 0, 0),\n    (-1, 1, 0),\n])\ndef test_add(a, b, expected):\n    assert a + b == expected","o":["1","3","6","9"],"a":1,"e":"`parametrize` runs the same test function once for each set of values in the list. Three tuples → three separate test cases, each reported as passed or failed on its own.\nThis avoids copy-pasting nearly identical tests, and one failing input does not hide the others.","r":"parametrize = same test, many inputs.","g":["parametrize","pytest","unit_test","fixture","assertion","deterministic"],"cat":"test"},{"id":"TST-03","t":"m","l":3,"q":"Which patch target makes this test intercept the HTTP call?","c":"# app/services.py\nfrom requests import get\n\ndef fetch_user(uid):\n    return get(f\"https://api.example.com/users/{uid}\").json()","o":["`patch(\"requests.get\")`","`patch(\"app.services.get\")`","`patch(\"requests.api.get\")`","`patch(\"get\")`"],"a":1,"e":"`from requests import get` creates a NEW name `get` inside the module `app.services`, pointing to the function.\n`patch(\"requests.get\")` replaces the name inside the requests module, but `app.services.get` still points to the original function, so the real HTTP call happens.\nRule: patch the name where it is USED (looked up), not where it is defined.","r":"Patch where the name is looked up.","g":["mock","stub","fake","autospec","http","test_isolation"],"cat":"test"},{"id":"TST-04","t":"m","l":2,"q":"An in-memory `UserRepository` that stores users in a dict and behaves like the real one is called a…","o":["Mock","Stub","Fake","Spy"],"a":2,"e":"These are all 'test doubles', stand-ins for real dependencies:\n- Fake: a simple but WORKING implementation (in-memory repository, fake email sender that stores messages in a list).\n- Stub: returns fixed answers ('always return this user').\n- Mock: pre-programmed and later checked: 'was send() called once with these arguments?'.\n- Spy: wraps a real object and records how it was called.","r":"Fake = working lightweight version of the real thing.","g":["fake","stub","mock","unit_test","integration_test","test_isolation","deterministic"],"cat":"test"},{"id":"TST-05","t":"m","l":1,"q":"How do you assert that code raises a `ValueError` in pytest?","o":["`assert raises(ValueError)` placed after the call","`with pytest.raises(ValueError): parse('x')`","`try/except` followed by `assert True`","`@pytest.mark.error` above the test"],"a":1,"e":"The test passes only if the code inside the `with` block raises ValueError; if no error happens, the test fails.\nYou can also check the message: `pytest.raises(ValueError, match=\"invalid\")`.\nA hand-written try/except that does nothing when no error occurs would pass silently and hide bugs.","r":"Expect an error → with pytest.raises(...).","g":["pytest","exception","assertion","unit_test","n_builtin_exc"],"fa":"`with pytest.raises(ValueError): parse(\"x\")`","cat":"test"},{"id":"TST-06","t":"m","l":2,"q":"Which is a common root cause of flaky tests?","o":["Using too many assertions in one single test","Depending on time, shared state or real network","Using fixtures to prepare the data for tests","Running the tests on a local developer machine"],"a":1,"e":"A flaky test sometimes passes and sometimes fails without any code change. Teams then stop trusting the test suite.\nTypical causes: depending on the current time, random values, test order, data left by other tests, real network calls, or `sleep()` used to wait for something.\nFix the cause (inject the clock, seed randomness, isolate data, mock the network, wait for conditions). Automatic retries only hide it.","r":"Flaky = non-deterministic. Remove the source of randomness.","g":["flaky_test","deterministic","test_isolation","mock","ci","n_sleep"],"fa":"Dependence on time, ordering, shared state, randomness or real network calls","cat":"test"},{"id":"TST-07","t":"m","l":2,"q":"Your project has 100% line coverage. What can you conclude?","o":["There are no bugs left anywhere in the code","Every line ran, but edge cases may be unchecked","Mutation testing is no longer needed at all","The tests run fast on every machine and in CI"],"a":1,"e":"Coverage measures which lines were EXECUTED during tests, not whether the results were checked. A test with no assertions still produces coverage.\nIt also misses combinations: a line can run while one important branch or input never gets tested.\nCoverage is good for finding untested code, not for proving correctness.","r":"Coverage shows what ran, not what was verified.","g":["coverage","edge_case","mutation_testing","unit_test","regression","assertion"],"fa":"Every line ran during tests, but not that the behavior was checked or that all branches and edge cases were covered","cat":"test"},{"id":"TST-08","t":"m","l":2,"q":"How do you reliably test code that depends on the current time?","o":["Run the test only at one specific hour of day","Inject a clock, or freeze time with freezegun","Add `time.sleep` calls inside of the test body","Skip those tests when they depend on the clock"],"a":1,"e":"Code that calls `datetime.now()` inside gives different results each time it runs, so tests can't predict it (and may fail at midnight or month-end).\nPass the time source in as a parameter, e.g. `is_expired(token, now)`, so tests give a fixed date. Or freeze time for the test with freezegun.\nThe same idea applies to random numbers and IDs.","r":"Time is a dependency: inject or freeze it.","g":["dependency_injection","deterministic","mock","fake","stub","unit_test"],"fa":"Inject a clock (or `now` function) as a dependency, or freeze time with a library like freezegun / time-machine","cat":"test"},{"id":"TST-09","t":"m","l":2,"q":"Best practice for integration tests that need PostgreSQL?","o":["Mock the whole ORM and assert on the calls made","Run real Postgres in a container, roll back per test","Use SQLite instead, since all SQL is standard","Point the tests at the shared production database"],"a":1,"e":"Integration tests check that your code really works with the real dependency. Mocking the ORM tests nothing real; SQLite behaves differently from Postgres (types, constraints, JSON, locking).\nStart a throwaway Postgres in Docker for the tests. Keep tests independent by rolling back each test's transaction or recreating the schema.\nNever touch production data in tests.","r":"Integration tests: real database in a container, isolated per test.","g":["integration_test","container","test_isolation","transaction","docker_compose","rollback"],"fa":"Use a real Postgres (e.g. in a container via testcontainers or docker compose) and isolate each test with a transaction rollback or fresh schema","cat":"test"},{"id":"TST-10","t":"m","l":3,"q":"What problem does consumer-driven contract testing (e.g. Pact) solve?","o":["It runs load tests against the deployed service","It checks providers still meet their consumers' needs","It compares UI screenshots to find the changes","It tests the database migrations of a service"],"a":1,"e":"Service A (consumer) calls service B (provider). If B renames a field, A breaks, and maybe nobody notices until production.\nWith contract tests, A records exactly which requests it sends and which response fields it needs (the contract). B's CI verifies that it still satisfies every consumer's contract.\nIt catches breaking API changes early without a full environment of all services.","r":"Contract tests = provider checks it still meets consumers' expectations.","g":["contract_test","microservices","api","ci"],"fa":"Verifying that a provider API still satisfies what its consumers expect, without running full end-to-end environments","cat":"test"},{"id":"TST-11","t":"m","l":3,"q":"What does property-based testing (e.g. Hypothesis) do?","o":["It tests only the properties of each object","It generates random inputs to check invariants","It measures how much code coverage tests have","It records HTTP traffic in order to replay it"],"a":1,"e":"Instead of writing examples one by one, you describe a rule that must ALWAYS be true, and the library tries hundreds of generated inputs, including nasty ones (empty, huge, unicode, negative).\nExample rule: sorting twice gives the same result as sorting once, and keeps the same length.\nWhen it finds a failure, it shrinks it to the smallest input that still fails, which makes debugging easy.","r":"Property-based = test rules on many generated inputs.","g":["property_based","edge_case","unit_test","assertion","deterministic"],"fa":"Generates many random inputs to check that invariants always hold, and shrinks failures to a minimal example","cat":"test"},{"id":"TST-12","t":"m","l":3,"q":"Mutation testing measures…","o":["The execution speed of the code under test","Test quality: it plants bugs and expects failures","The memory usage of the code during a run","How often the code changes in the repository"],"a":1,"e":"The tool makes small changes to your code, for example `>` into `>=` or `+` into `-`, and runs your tests for each change.\nIf the tests still pass with the bug in place, that mutant 'survived', meaning your tests do not really check that behavior.\nIt is slow, so it is typically run on important modules. Tools: mutmut (Python), Stryker (JS).","r":"Mutation testing = do my tests catch deliberately planted bugs?","g":["mutation_testing","coverage","unit_test","assertion","regression","ci"],"fa":"How good your tests are: it injects small bugs (mutants) into the code and checks whether tests fail","cat":"test"},{"id":"TST-13","t":"m","l":1,"q":"What is the Arrange-Act-Assert pattern?","o":["A deployment process for the releases of a team","Setup, one action, then assertions on the result","A mocking library that is used for Python tests","An Agile ceremony that teams hold every sprint"],"a":1,"e":"A clear test has three parts:\n- Arrange: prepare data and objects.\n- Act: do the ONE thing being tested.\n- Assert: check the result.\nOne behavior per test, with a descriptive name like `test_withdraw_more_than_balance_raises`, makes failures easy to understand.","ec":"def test_withdraw_reduces_balance():\n    account = Account(balance=100)      # Arrange\n    account.withdraw(30)                # Act\n    assert account.balance == 70        # Assert","r":"Arrange → Act → Assert.","g":["aaa","unit_test","assertion","object"],"fa":"Structure each test as setup, a single action under test, then assertions on the outcome","cat":"test"},{"id":"TST-14","t":"m","l":2,"q":"What is `conftest.py` for in pytest?","o":["Configuring the linters of the whole project","Sharing fixtures and hooks with the tests below it","Storing the test data files of the project","Defining the CI pipelines of the repository"],"a":1,"e":"Fixtures defined in a `conftest.py` file are automatically available to every test in the same folder and its subfolders. You don't import them.\nTypical content: database fixtures, a test client for your app, shared fake objects.\nGeneral pytest settings go in `pyproject.toml` or `pytest.ini`.","r":"conftest.py = shared fixtures for a folder of tests.","g":["conftest","fixture","pytest","n_pyproject"],"fa":"Sharing fixtures and hooks with all tests in that directory and below, without importing them","cat":"test"},{"id":"TST-15","t":"m","l":1,"q":"You are fixing a production bug. What is the recommended first step in code?","o":["Fix it directly in the code and deploy it","Write a failing test that reproduces the bug","Add more logging only and wait for it to happen","Rewrite the whole module that has the bug"],"a":1,"e":"A failing test proves you understood and reproduced the bug. When it turns green, you know the fix works.\nThe test then stays in the suite as a regression test: if anyone reintroduces the bug later, it fails immediately.","r":"Bug fix = failing test first, then the fix.","g":["regression","unit_test","tdd","edge_case","assertion"],"fa":"Write a test that reproduces the bug and fails, then fix it so the test passes","cat":"test"},{"id":"TST-16","t":"m","l":2,"q":"Why should tests not depend on execution order?","o":["Test order is always alphabetical, so it is safe","Order can change; hidden dependencies cause failures","It makes the tests run slower than they should","pytest forbids tests that rely on any order"],"a":1,"e":"If test B only passes because test A created some data first, then B fails when run alone, in parallel or in a different order.\nEach test should create what it needs and clean up after itself.\nPlugins like pytest-randomly shuffle the order to reveal hidden dependencies; pytest-xdist runs tests in parallel.","r":"Every test must work alone, in any order.","g":["test_isolation","flaky_test","fixture","deterministic","unit_test","parametrize"],"fa":"Order can change (parallel runs, random ordering, running one test alone); hidden dependencies cause failures that are hard to reproduce","cat":"test"},{"id":"TST-17","t":"m","l":2,"q":"Which assertion verifies that a mock was called exactly once with specific arguments?","o":["`assert mock.called is True and mock.count == 1`","`mock.assert_called_once_with(42, retry=True)`","`assert mock(42, retry=True) is not None`","`mock.verify(42, retry=True, times=1)`"],"a":1,"e":"`unittest.mock` objects record every call made to them. `assert_called_once_with(...)` fails if the mock was called zero times, more than once, or with different arguments.\nOther useful ones: `assert_called_with` (last call), `assert_not_called()`, and `mock.call_args_list` to inspect every call.","r":"Check how a mock was called with assert_called_once_with.","g":["mock","assertion","unit_test","stub","fake"],"cat":"test"},{"id":"TST-18","t":"m","l":3,"q":"What does `patch(..., autospec=True)` add?","o":["Faster mocks, since they skip the real object","The mock uses the real signature, so bad calls fail","Automatic assertions on every call that is made","Real network calls for the patched dependency"],"a":1,"e":"A plain Mock accepts any method name and any arguments. If the real function's signature changes, your tests keep passing while production breaks.\nWith `autospec=True`, the mock copies the real object's methods and parameters, so a call that would be invalid on the real thing also fails in the test.","r":"autospec = mocks that respect the real signature.","g":["autospec","mock","stub","fake","unit_test","dependency_injection"],"fa":"The mock copies the real object's signature, so calls with wrong arguments or nonexistent methods fail","cat":"test"},{"id":"TST-19","t":"m","l":2,"q":"How do you test a FastAPI endpoint without calling the real database?","o":["You cannot do it without starting a real database","`TestClient` plus `dependency_overrides[get_db]` fake","Patch `fastapi.FastAPI` itself in the test setup","Run the server and call it with curl in the tests"],"a":1,"e":"`TestClient` sends requests to your app in memory, without starting a real server.\nBecause FastAPI uses dependency injection, you can swap any dependency for the test: `app.dependency_overrides[get_db] = lambda: fake_db`.\nRemember to clear the overrides after each test (a fixture is a good place).","ec":"client = TestClient(app)\napp.dependency_overrides[get_db] = lambda: FakeDB()\n\ndef test_read_user():\n    r = client.get(\"/users/1\")\n    assert r.status_code == 200","r":"FastAPI tests: TestClient + dependency_overrides.","g":["dependency_injection","fake","mock","stub","integration_test","endpoint","unit_test"],"fa":"Use `TestClient(app)` and replace the DB dependency with `app.dependency_overrides[get_db] = fake_db`","cat":"test"},{"id":"TST-20","t":"m","l":2,"q":"What is the purpose of a load test with a tool like Locust or k6?","o":["To find syntax errors in the source code files","To measure throughput, latency and errors under load","To check the code style of the whole project","To test the layout of the user interface pages"],"a":1,"e":"A load test simulates many users at once to see how the system behaves: how many requests per second it handles, how slow responses get, and when errors start.\nLook at p95/p99 latency (the slowest requests), not only the average, and watch CPU, database and connection pools to find the bottleneck.\nRun it against a production-like environment.","r":"Load test = how does it behave with many users?","g":["load_test","latency","throughput","connection_pool","n_cpu"],"fa":"Measure throughput, latency percentiles and error rates under expected and peak traffic, and find the breaking point","cat":"test"},{"id":"TST-21","t":"m","l":1,"q":"What are smoke tests?","o":["Tests that are run for fire alarms in buildings","A small, fast set of checks of critical paths","Exhaustive regression suites that cover everything","Security scans that look for known vulnerabilities"],"a":1,"e":"The name comes from hardware: switch it on and check that no smoke comes out.\nAfter a deploy, a few quick checks confirm the basics: the health endpoint answers, users can log in, one key page loads and one key action works.\nIf a smoke test fails, roll back immediately.","r":"Smoke test = quick 'is it basically alive?' check.","g":["smoke_test","e2e_test","integration_test","ci","pipeline"],"fa":"A small, fast set of checks that the most critical paths work, often run right after a deploy","cat":"test"},{"id":"TST-22","t":"f","l":2,"q":"How do you decide what to test and how much?","a":"- Test behavior and contracts, not internal details.\n- Prioritize by risk: business-critical logic, money, security, complex branching, places that had bugs before.\n- Pyramid: many unit tests for pure logic, integration tests at boundaries (database, APIs), a few end-to-end tests for critical user journeys.\n- Edge cases: empty, null, limits, duplicates, concurrency, failing dependencies.\n- Keep tests fast and deterministic so people actually run them.\n- Use coverage to find gaps, not as a goal in itself.","g":["test_pyramid","edge_case","coverage","integration_test","e2e_test","deterministic","unit_test"],"cat":"test"},{"id":"TST-23","t":"f","l":3,"q":"How would you test code that calls an external payment API?","a":"- Hide the provider behind your own interface (`PaymentGateway`) and inject it.\n- Unit tests: use a fake or mock of your interface; cover success, card declined, timeout, duplicate request.\n- Adapter tests: stub HTTP with `responses`/`respx` or recorded responses; check the request format and how errors are mapped.\n- A few integration tests against the provider's sandbox/test mode (often nightly).\n- Test idempotency keys and webhook signature checks.\n- Never call the real production API from tests.","g":["fake","mock","dependency_injection","idempotent","api","integration_test","unit_test","webhook"],"cat":"test"},{"id":"TST-24","t":"m","l":1,"q":"Unit test vs integration test?","o":["They are the same thing under two different names","Unit: one piece alone. Integration: parts together","Integration tests are always done manually by hand","Unit tests always need a running server to work"],"a":1,"e":"Unit test: tiny and fast (milliseconds). Tests one function with its dependencies replaced by fakes. When it fails, you know exactly where.\nIntegration test: checks that real parts fit together: your repository with a real PostgreSQL, or your API with its middleware. Slower but catches problems unit tests can't.\nEnd-to-end tests go further and test the whole system like a user.","r":"Unit = one piece alone. Integration = pieces together.","g":["unit_test","integration_test","e2e_test","z_database","class","middleware"],"fa":"A unit test checks one small piece (a function or class) in isolation; an integration test checks several parts working together, e.g. code + real database","cat":"test"},{"id":"TST-25","t":"m","l":1,"q":"How does pytest find tests by default?","o":["It runs every Python file in the project folder","Files `test_*.py`, functions `test_*`, classes `Test*`","Only files in a folder that is named pytest","You must register each test by hand in a file"],"a":1,"e":"Run `pytest` in your project and it searches the folders for files named `test_something.py`, then runs every function whose name starts with `test_`.\nIf you name a function `check_login()`, pytest will silently ignore it.\nUseful options: `pytest -k login` (only matching names), `pytest -x` (stop at first failure), `pytest -v` (verbose).","r":"pytest runs test_*.py files and test_* functions.","g":["pytest","conftest","fixture","unit_test","parametrize"],"fa":"Files named `test_*.py` or `*_test.py`, functions starting with `test_`, and classes starting with `Test`","cat":"test"},{"id":"TST-26","t":"m","l":1,"q":"What happens when an `assert` statement in a pytest test is false?","c":"def test_total():\n    assert calculate_total([10, 20]) == 30","o":["Nothing happens and the test continues to run","The test fails, and pytest shows the compared values","Python crashes with a traceback and stops all tests","The test is skipped and flagged in the report"],"a":1,"e":"`assert condition` raises an AssertionError when the condition is false. pytest catches it, marks the test as FAILED and shows a detailed message, e.g. `assert 25 == 30`, so you see what the code actually returned.\nIf the condition is true, nothing happens and the test passes.","r":"assert false → test fails with the compared values shown.","g":["assertion","pytest","unit_test","exception","fixture","regression"],"fa":"The test fails, and pytest shows the values that were compared","cat":"test"},{"id":"TST-27","t":"m","l":1,"q":"In testing, what is a mock?","o":["A failing test that is written before the code","A fake object that stands in for a real dependency","A copy of the production environment for testing","A very slow test that runs once in a while"],"a":1,"e":"Real dependencies can be slow, cost money, or be unpredictable (sending an email, charging a card, calling an API).\nA mock stands in for them during a test: you decide what it returns, and afterwards you can check how your code called it, e.g. 'was send_email called once with this address?'.\nIn Python: `unittest.mock.Mock` and `patch`.","r":"Mock = stand-in that you control and inspect.","g":["mock","api","dependency","object","z_patch"],"fa":"A fake object that replaces a real dependency (like an API client) and records how it was used","cat":"test"},{"id":"TST-28","t":"m","l":1,"q":"What is the main benefit of an automated test suite?","o":["It makes the application run faster in production","It catches regressions in minutes, before users do","It replaces the need for code reviews entirely","It writes the documentation automatically for you"],"a":1,"e":"Without tests, every change risks breaking something elsewhere, and you only find out in production.\nWith a good test suite, CI runs all tests on every change; a broken behavior fails a test right away. That makes refactoring and adding features much safer and faster.\nTests also document how code is supposed to behave.","r":"Tests = safety net against regressions.","g":["regression","ci","unit_test","integration_test","pipeline","coverage"],"fa":"It catches regressions: when a change breaks something that used to work, you find out in minutes, not from users","cat":"test"},{"id":"TST-29","t":"m","l":1,"q":"What does test coverage measure?","o":["How many tests exist in the project in total","The share of lines or branches run by the tests","How fast the tests of the suite finally run","How many bugs exist in the code of the project"],"a":1,"e":"A coverage tool (e.g. `pytest --cov`) watches which lines run during the tests and reports a percentage, plus which lines were never executed.\nThose uncovered lines are code no test checks at all, good places to add tests.\nHigh coverage does not guarantee good tests: it doesn't check that assertions are meaningful.","r":"Coverage = % of code executed by tests.","g":["coverage","unit_test","mutation_testing","regression","test_pyramid","pytest"],"fa":"The percentage of code lines (or branches) executed while the tests run","cat":"test"},{"id":"TST-30","t":"m","l":1,"q":"Which is an edge case for a function that returns the average of a list?","o":["A list with 3 normal numbers","An empty list (division by zero)","A list of positive integers","A list sorted ascending"],"a":1,"e":"Edge cases are unusual or extreme inputs at the boundaries, where bugs like to hide: empty input, one element, zero, negative numbers, very large values, duplicates, None.\nAn average divides by the length; with an empty list that is division by zero. Decide what should happen (return None? raise ValueError?) and test it.","r":"Always test empty, one, zero, negative, huge, None.","g":["edge_case","unit_test","assertion","exception","null","n_builtin_exc"],"cat":"test"},{"id":"TST-31","t":"m","l":1,"q":"Which describes a good unit test?","o":["Slow but thorough, and depends on the internet","Fast, isolated from others, and deterministic","Tests many unrelated behaviors at the same time","Only runs on the CI server and never locally"],"a":1,"e":"Good unit tests run in milliseconds (so you run them constantly), don't depend on other tests or on the network/database (isolated), and always give the same result (deterministic).\nEach test checks one behavior and has a name that explains it. If a test is slow or random, people stop trusting and running it.","r":"Good unit test = fast, isolated, deterministic.","g":["unit_test","deterministic","test_isolation","z_database"],"fa":"Fast, isolated from other tests and external systems, and deterministic (same result every run)","cat":"test"},{"id":"TST-32","t":"m","l":1,"q":"What is Selenium WebDriver?","o":["A library that drives a real browser from code","A database in which test results are stored","A CSS framework that is used to style reports","A Java build tool that compiles and runs tests"],"a":0,"e":"Selenium automates browsers. Your test code (Java, Python, JS...) sends commands to a driver (ChromeDriver, GeckoDriver), which controls a real browser: open a URL, find elements, click, type, and check the text on screen.\nUsed for end-to-end (E2E) UI tests that check complete user flows (login, checkout).\nSelenium Manager (built in since 4.6) downloads the right driver automatically.","ec":"WebDriver driver = new ChromeDriver();\ndriver.get(\"https://example.com/login\");\ndriver.findElement(By.id(\"email\")).sendKeys(\"ana@example.com\");\ndriver.findElement(By.cssSelector(\"button[type=submit]\")).click();\ndriver.quit();","r":"Selenium = code that drives a real browser.","g":["t_selenium","e2e_test","state","z_browser","z_library","z_java"],"fa":"A library that controls a real web browser (click, type, read) from code to automate UI tests, using drivers such as ChromeDriver","cat":"test"},{"id":"TST-33","t":"m","l":2,"q":"Which locator strategy is generally the most robust in Selenium?","o":["A stable attribute such as `id` or `data-testid`","Absolute XPath like `/html/body/div[3]/div[2]/button`","The position number of the element","The text color of the element"],"a":0,"e":"Locators find elements: `By.id`, `By.name`, `By.cssSelector`, `By.xpath`, `By.linkText`.\nA locator breaks when the page changes. Absolute XPath breaks with any layout change. Stable hooks are best: `id` or a test attribute like `data-testid=\"submit\"`, agreed with the front-end team.\nCSS selectors are usually faster and more readable than XPath; use XPath when you need text or parent navigation.","r":"Prefer id / data-testid. Avoid long absolute XPath.","g":["t_locator","n_testid","selector","css"],"fa":"A dedicated, stable attribute such as `id` or `data-testid`; avoid long absolute XPath tied to page layout","cat":"test"},{"id":"TST-34","t":"m","l":2,"q":"Why is `Thread.sleep(5000)` a bad way to wait in UI tests, and what is better?","o":["It always waits fully; use explicit waits instead","It crashes the browser when the time is long","Selenium forbids it in all of its drivers","It is the best approach for slow web pages"],"a":0,"e":"Pages load asynchronously, so tests must wait for elements. A fixed sleep is either too long (slows the suite) or too short (random failures).\nExplicit wait: `new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(...))` polls until the condition is true or times out.\nImplicit waits apply globally to element lookups; do not mix implicit and explicit waits, since the total time becomes unpredictable.","ec":"WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));\nWebElement banner = wait.until(\n    ExpectedConditions.visibilityOfElementLocated(By.id(\"success\")));","r":"Wait for a condition, not for a fixed time.","g":["t_explicit_wait","flaky_test","t_locator","t_selenium","e2e_test","deterministic"],"fa":"It always waits the full time (slow) and can still be too short (flaky); use explicit waits (`WebDriverWait` with expected conditions) that continue as soon as the condition is true","cat":"test"},{"id":"TST-35","t":"m","l":2,"q":"What is the Page Object Model (POM)?","o":["Each page is a class with locators and actions","A way to store photos that tests will compare","A Maven plugin that builds the pages of the app","A database schema that describes the pages"],"a":0,"e":"Without POM, locators are scattered across tests; when a button's id changes you edit dozens of tests.\nWith POM, `LoginPage` has methods like `loginAs(user, pass)`; tests call them and never mention locators. If the UI changes, you fix the page class once.\nTests become readable: `loginPage.loginAs(\"ana\", \"secret\"); assertTrue(dashboard.isVisible());`","ec":"public class LoginPage {\n    private final WebDriver driver;\n    public LoginPage(WebDriver d) { this.driver = d; }\n\n    public DashboardPage loginAs(String user, String pass) {\n        driver.findElement(By.id(\"user\")).sendKeys(user);\n        driver.findElement(By.id(\"pass\")).sendKeys(pass);\n        driver.findElement(By.id(\"login\")).click();\n        return new DashboardPage(driver);\n    }\n}","r":"POM = one class per page; locators live there, not in tests.","g":["t_pom","design_pattern","t_locator","state","j_final"],"fa":"A design pattern where each page (or component) is a class holding its locators and actions, so tests read like user steps and a UI change is fixed in one place","cat":"test"},{"id":"TST-36","t":"m","l":2,"q":"What does `StaleElementReferenceException` mean?","o":["The element was re-rendered; find it again","The browser is out of date and needs an update","The driver executable is missing from the system","The element is hidden behind another element"],"a":0,"e":"Selenium keeps a reference to a DOM element. If the page re-renders (React updates, AJAX refresh, navigation), the old element is replaced by a new one even if it looks identical, and the old reference becomes stale.\nFix: re-locate the element right before using it, do not store `WebElement` objects for long, and wait for the page to settle (explicit waits). Page objects that look up elements on each action avoid this.","r":"Stale = the DOM element was replaced; locate it again.","g":["t_locator","flaky_test","dom","t_explicit_wait","react"],"fa":"The element you found earlier was removed or re-rendered in the DOM, so the stored reference is no longer valid; find it again (and wait properly)","cat":"test"},{"id":"TST-37","t":"m","l":3,"q":"What is Selenium Grid used for?","o":["Running tests in parallel across many machines","Drawing tables of results for the test reports","Managing the databases that tests rely upon","Compiling the Java code of the test project"],"a":0,"e":"One machine running tests one by one makes a big UI suite slow. Selenium Grid has a hub/router and several nodes; tests ask for a browser (Chrome 120 on Linux) and the Grid sends them to a free node, running many in parallel.\nTypically deployed with Docker or Kubernetes, or replaced by cloud services (BrowserStack, Sauce Labs).\nParallel tests must be independent: separate data, no shared state.","r":"Grid = parallel, cross-browser execution.","g":["t_selenium","e2e_test","t_pom","docker_image","ci","kubernetes"],"fa":"Running tests in parallel across many browsers, versions and machines (or containers)","cat":"test"},{"id":"TST-38","t":"m","l":2,"q":"Which JUnit 5 annotations run before each test and mark a parameterized test?","o":["`@BeforeEach` and `@ParameterizedTest`","`@SetupAll` and `@LoopTest` annotations","`@InitEach` and `@ManyTimes` annotations","`@BeforeTest` and `@Params` annotations"],"a":0,"e":"JUnit 5 (Jupiter) basics:\n- `@Test`: a test method.\n- `@BeforeEach` / `@AfterEach`: run around every test (set up and clean up).\n- `@BeforeAll` / `@AfterAll`: once per class (static).\n- `@ParameterizedTest` with `@ValueSource`, `@CsvSource`: run one test with many inputs.\n- `@DisplayName`, `@Disabled`, `@Nested`.\nAssertions: `assertEquals`, `assertTrue`, `assertThrows`. AssertJ offers fluent alternatives.","ec":"@ParameterizedTest\n@CsvSource({\"2,3,5\", \"10,-4,6\"})\nvoid adds(int a, int b, int expected) {\n    assertEquals(expected, a + b);\n}","r":"@BeforeEach = per test. @ParameterizedTest = many inputs.","g":["unit_test","t_junit","parametrize","fixture","assertion"],"cat":"test"},{"id":"TST-39","t":"m","l":2,"q":"Selenium, Playwright and Cypress: what is a fair comparison?","o":["Selenium is mature; Playwright and Cypress auto-wait","They are identical in every feature that they have","Selenium is a database for storing test results","Cypress supports every programming language there is"],"a":0,"e":"- Selenium WebDriver: oldest and most widespread, supports Java, Python, C#, JS and all major browsers; very common in enterprise Java shops; you handle waits yourself.\n- Playwright (Microsoft): multi-browser, multi-language, built-in auto-waiting, tracing, fast.\n- Cypress: JavaScript/TypeScript only, runs inside the browser, great debugging, more limited cross-tab and cross-browser support.\nSelenium is still very common in Java teams, so know WebDriver, waits, locators and POM.","r":"Selenium = standard and flexible; Playwright/Cypress = modern with auto-waiting.","g":["t_selenium","javascript","typescript","t_locator"],"fa":"Selenium: mature, many languages and browsers, W3C standard; Playwright and Cypress: newer, with auto-waiting and developer-friendly tooling (Cypress runs in the browser, JS only)","cat":"test"},{"id":"TST-40","t":"m","l":1,"q":"Why should the UI test automation suite be small compared to unit tests?","o":["UI tests are slow and brittle, so keep only a few","UI tests are free to maintain, so write many more","Unit tests cannot find real bugs in the logic","Browsers are very fast, so UI tests are cheap"],"a":0,"e":"Test pyramid: many unit tests (fast, cheap), fewer integration tests, very few UI/E2E tests (slow, depend on browsers, network, data).\nUse UI automation for the most important user journeys (login, purchase) and smoke tests after deployment.\nTest business rules, validation and edge cases through unit or API tests.","r":"Few UI tests, many unit tests.","g":["test_pyramid","e2e_test","state","unit_test","integration_test","smoke_test"],"fa":"UI tests are slow, brittle and expensive to maintain, so keep a few critical end-to-end flows and test most logic at lower levels (the test pyramid)","cat":"test"},{"id":"TST-41","t":"f","l":2,"q":"How would you design a maintainable Selenium (Java) test automation framework?","a":"- Stack: Java, JUnit 5 (or TestNG), Selenium WebDriver, Maven, AssertJ, reporting (Allure).\n- Structure: Page Object Model; small component classes for shared widgets; tests only describe user steps.\n- Stability: stable locators (`data-testid`), explicit waits only, no `Thread.sleep`, retries only for known infrastructure noise.\n- Data: create test data through the API or database before the test; independent tests that can run in any order and in parallel.\n- Execution: headless Chrome in CI (GitHub Actions/Jenkins), Selenium Grid or Docker for parallel and cross-browser runs; screenshots and logs on failure.\n- Scope: few E2E flows for critical journeys; the rest at unit and API level.","g":["api","t_selenium","t_pom","t_explicit_wait","n_testid","t_locator","t_junit","v_maven"],"cat":"test"},{"id":"TST-42","t":"m","l":0,"q":"Why do developers write tests?","o":["To check the code works as expected, early on","To make the program run faster in production","Because every compiler requires them to build","To increase the total file size of the program"],"a":0,"e":"Without tests, every change might silently break something else and you only find out when users complain.\nWith tests, you run a command and see in seconds whether the important behavior still works.\nTests also act as living documentation of how the code should behave.","r":"Tests = a safety net for changes.","g":["regression","unit_test","tdd","coverage","ci","assertion"],"fa":"To check that the code behaves as expected and to catch problems early, especially when the code changes later","cat":"test"},{"id":"TST-43","t":"m","l":0,"q":"Manual testing vs automated testing?","o":["Manual: a person runs steps; automated: code does","Automated tests need no code to be written at all","Manual tests are always better than automated ones","They are the same thing under two different names"],"a":0,"e":"Manual testing is good for exploring, judging usability and trying unexpected things.\nAutomated tests are written once and run on every change (CI), so they are ideal for repeated checks like regression tests.\nTools: JUnit (Java), pytest (Python), Selenium (browser UI).","r":"Manual = a human. Automated = code.","g":["z_manual_vs_auto","ci","pytest","z_java","state"],"fa":"Manual: a person performs the steps and checks the result; automated: code runs the checks quickly and repeatedly","cat":"test"},{"id":"TST-44","t":"m","l":0,"q":"What are a test case and a test suite?","o":["A case checks one scenario; a suite groups cases","A test case is a computer case; a suite is a room","A suite is one single test; a case is many tests","Both of them are error messages shown in pytest"],"a":0,"e":"Test case: 'when I log in with a wrong password, I should see an error message and not enter'. It has steps, input data and an expected result.\nTest suite: a collection of test cases, for example 'all login tests' or 'all tests of the project'.\nIn code, one test method is usually one case, and a test class or folder is a suite.","r":"Case = one scenario. Suite = a group of cases.","g":["z_test_case","unit_test","regression","assertion","fixture"],"fa":"A test case checks one scenario against an expected result; a suite is a group of test cases run together","cat":"test"},{"id":"TST-45","t":"m","l":0,"q":"What is regression testing?","o":["Re-running tests to check old features still work","Testing only the new feature that was just added","Testing the database backup that was just made","Testing the speed of the app on old hardware"],"a":0,"e":"A regression is when something that used to work breaks after a change.\nRegression testing re-checks old behavior every time you change the code. It is the main reason to automate tests: running hundreds of old checks by hand every release is not realistic.\nWhen you fix a bug, you add a test for it, which keeps that bug from coming back.","r":"Regression test = did my change break something old?","g":["regression","ci","unit_test","smoke_test","e2e_test","coverage"],"fa":"Re-running tests after a change to make sure existing features still work","cat":"test"},{"id":"TST-46","t":"m","l":0,"q":"What does QA stand for, and what does a QA engineer do?","o":["Quality Assurance: ensures quality through testing","Quick Answer: replies to the customers by email","Query Application: writes the SQL for the apps","Quality Angle: designs the logos of the company"],"a":0,"e":"QA engineers (or testers) design test cases, run manual and automated tests, report bugs clearly and check fixes.\nSome focus on automation: writing frameworks with tools such as Selenium. Developers also test their own code, so quality is a team responsibility.\nA good bug report has steps to reproduce, expected result, actual result, and environment.","r":"QA = Quality Assurance.","g":["z_qa","unit_test","e2e_test","load_test","z_manual_vs_auto","ci"],"fa":"Quality Assurance: helps make sure the software meets quality expectations through testing, test automation and better processes","cat":"test"},{"id":"TST-47","t":"m","l":0,"q":"What is Selenium?","o":["An umbrella project of tools to automate browsers","A database that stores the results of tests","A cloud provider that rents servers by the hour","A Java framework for building backend servers"],"a":0,"e":"Selenium can open a real browser and do what a user does: click, type, read text.\nIts parts: WebDriver (the core, a common interface for many browsers), Selenium IDE (records and plays back actions) and Selenium Grid (runs tests in parallel on many machines).\nIt supports Java, Python, C#, Ruby, JavaScript and Kotlin.","r":"Selenium = automate browsers for UI tests.","g":["t_selenium","z_browser","state","z_java","javascript","z_ide"],"fa":"An umbrella project of tools and libraries for automating web browsers, mostly used to test web UIs","cat":"test"},{"id":"TST-48","t":"m","l":0,"q":"What are JUnit and pytest?","o":["Testing frameworks for Java and Python respectively","Cloud services that run tests on remote servers","Databases that store the results of test runs","Build tools that compile and package the projects"],"a":0,"e":"A testing framework gives you a standard way to write test methods, check results with assertions, set up data and see a report.\nJUnit is the main one for Java (JUnit 5 introduced the Jupiter style; JUnit 6 is the newest major version and requires Java 17 or newer). pytest is the most popular for Python.\nBuild tools like Maven run them with `mvn test`.","r":"JUnit = Java tests. pytest = Python tests.","g":["t_junit","pytest","assertion","z_java","z_framework","n_mvn_cmds"],"fa":"Testing frameworks: JUnit for Java and pytest for Python, used to write and run automated tests","cat":"test"},{"id":"BEH-01","t":"f","l":1,"q":"What is the STAR method and how long should an answer be?","a":"- Situation: context in 1-2 sentences.\n- Task: your responsibility or goal.\n- Action: what YOU did, in detail (use 'I', not 'we'). This is ~60% of the answer.\n- Result: measurable outcome + what you learned.\n- Aim for 1.5-2 minutes. Prepare 6-8 stories you can adapt to many questions.","g":["n_b_impact","n_b_ownership","z_behavioral","n_star"],"cat":"beh"},{"id":"BEH-02","t":"f","l":1,"q":"\"Tell me about yourself.\"","a":"- Present, past, future in ~90 seconds.\n- Present: current role and the impact you have now.\n- Past: 1-2 experiences that explain how you got here (engineering background, building software tools on the job).\n- Future: why this role is the logical next step.\n- Keep it technical and specific; end with a hook the interviewer can ask about.\n- Story idea: a Python tool you built that replaced a manual process, with its measurable result.","g":["n_b_tellme","n_star","n_b_career","n_b_impact"],"cat":"beh"},{"id":"BEH-03","t":"f","l":2,"q":"\"Tell me about the most challenging technical problem you solved.\"","a":"- Pick a problem with real ambiguity and stakes (production/field issue, hard bug, performance).\n- Explain constraints and why it was hard.\n- Walk through your debugging process: hypotheses, data, tools, dead ends.\n- Result with numbers (time saved, errors reduced, uptime).\n- What you would do differently; what you changed to prevent recurrence.","g":["n_star","n_b_ownership","n_b_impact","z_trade_off","n_b_learning"],"cat":"beh"},{"id":"BEH-04","t":"f","l":2,"q":"\"Tell me about a time you disagreed with a teammate or manager.\"","a":"- Show you disagree on ideas, respectfully, with data.\n- Situation and both positions fairly stated.\n- Actions: listened, asked questions, proposed an experiment or prototype, escalated appropriately if needed.\n- Result: decision made; if you lost, you committed fully ('disagree and commit').\n- Avoid stories where the other person is the villain.","g":["n_b_conflict","n_star","n_b_teamwork","z_stakeholder"],"cat":"beh"},{"id":"BEH-05","t":"f","l":2,"q":"\"Tell me about a time you failed or made a mistake.\"","a":"- Choose a real mistake with real consequences (not a disguised strength).\n- Own it clearly without blaming others.\n- How you detected it, communicated it, and fixed it fast.\n- What you changed afterwards (tests, checklist, monitoring, process).\n- Interviewers look for accountability and learning.","g":["n_b_failure","n_star","n_b_ownership","n_b_learning","postmortem"],"cat":"beh"},{"id":"BEH-06","t":"f","l":2,"q":"\"Tell me about a time you had a tight deadline.\"","a":"- Context and why the deadline was fixed.\n- How you prioritized: cut scope to the essentials, negotiated trade-offs, flagged risks early.\n- Communication with stakeholders.\n- Result: delivered (or what was delivered), quality kept where it mattered.\n- Lesson about estimation or planning.","g":["n_b_deadline","n_star","z_trade_off","n_b_impact"],"cat":"beh"},{"id":"BEH-07","t":"f","l":1,"q":"\"Tell me about a project you are most proud of.\"","a":"- Pick one with clear personal ownership and technical depth.\n- Problem, users, why it mattered.\n- Your architecture/design decisions and trade-offs.\n- Hardest part and how you solved it.\n- Impact with metrics and what you learned.\n- Be ready for deep follow-up questions on any detail.","g":["n_b_impact","n_star","n_b_ownership","n_b_teamwork","z_trade_off"],"cat":"beh"},{"id":"BEH-08","t":"f","l":2,"q":"\"Tell me about a time you received critical feedback.\"","a":"- Specific feedback, not vague.\n- Your initial reaction (honest) and how you processed it.\n- Concrete actions you took to improve.\n- Evidence of change (later feedback, results).\n- Shows coachability and self-awareness.","g":["n_b_feedback","n_star","n_b_learning","n_b_ownership"],"cat":"beh"},{"id":"BEH-09","t":"f","l":3,"q":"\"How do you handle ambiguous or changing requirements?\"","a":"- Clarify goals: what problem, for whom, what does success look like.\n- Ask questions, write down assumptions, confirm with stakeholders.\n- Build small: prototype or MVP, get feedback early.\n- Design for change where cheap (clean boundaries, config).\n- Give a STAR example where you turned vague requests into a clear spec.","g":["n_b_ambiguity","b_agile","b_user_story","z_stakeholder","z_mvp","n_b_feedback","n_star"],"cat":"beh"},{"id":"BEH-10","t":"f","l":1,"q":"\"Tell me about a time you had to learn a new technology quickly.\"","a":"- Why you needed it and the time constraint.\n- Your learning strategy: official docs, small spike project, reading existing code, asking experts.\n- How you applied it to deliver something real.\n- Result and how you shared the knowledge (docs, demo).\n- Signals: self-direction and fast ramp-up.","g":["n_b_learning","n_star","n_b_ownership"],"cat":"beh"},{"id":"BEH-11","t":"f","l":2,"q":"\"Tell me about a time you improved a process or automated something.\"","a":"- The pain: manual, slow, error-prone work (quantify hours or error rate).\n- Your initiative: nobody asked, or you proposed it.\n- Solution: script, tool, CI step, template; how you got adoption.\n- Result: time saved per week, errors avoided, people using it.\n- Great place to show software skills from a non-software role.","g":["n_b_impact","n_b_ownership","ci","z_devops","n_star"],"cat":"beh"},{"id":"BEH-12","t":"f","l":3,"q":"\"Tell me about a difficult stakeholder or customer.\"","a":"- Understand their underlying concern (pressure, risk, past experience).\n- Actions: active listening, clear expectations, regular updates, translate technical constraints into business terms.\n- Find a compromise or alternative that serves the real need.\n- Result: relationship and outcome.\n- Stay professional and empathetic in the telling.","g":["z_stakeholder","n_b_conflict","n_star","n_b_comm"],"cat":"beh"},{"id":"BEH-13","t":"f","l":1,"q":"\"Why are you moving into a software engineering role / why this company?\"","a":"- Motivation framed positively: toward building software, not away from the old job.\n- Evidence of commitment: projects, tools shipped, courses, open source, measurable results.\n- Transferable strengths: domain knowledge, debugging under pressure, working with users in the field, documentation.\n- Company: something specific about product, engineering culture or tech stack (research it).\n- Connect your skills to what the team needs.","g":["n_b_motivation","n_b_career","n_b_tellme","z_behavioral","n_b_strengths"],"cat":"beh"},{"id":"BEH-14","t":"f","l":3,"q":"\"Tell me about a time you helped or mentored someone.\"","a":"- Who they were and what they struggled with.\n- How you helped: pairing, code reviews, documentation, explaining the why, letting them own the solution.\n- Result: their growth or team impact.\n- Shows collaboration and leadership without a title.","g":["n_b_mentoring","n_star","n_b_teamwork","z_code_review"],"cat":"beh"},{"id":"BEH-15","t":"f","l":2,"q":"\"How do you prioritize when you have several urgent tasks?\"","a":"- Clarify impact and urgency (who is blocked, customer impact, deadlines).\n- Make priorities visible and agree with your manager/stakeholders.\n- Quick wins that unblock others first; time-box investigations.\n- Communicate what will slip and when.\n- STAR example with a concrete outcome.","g":["n_b_deadline","z_trade_off","n_b_comm","b_kanban","n_star"],"cat":"beh"},{"id":"BEH-16","t":"f","l":1,"q":"What good questions can you ask the interviewer at the end?","a":"- What does success look like in this role after 3 and 6 months?\n- What are the biggest technical challenges the team is facing right now?\n- How do code review, testing and deployment work here? How often do you ship?\n- How are decisions made on architecture?\n- How do engineers grow here (mentoring, learning time, promotion)?\n- What do you enjoy most about working here?\n- Avoid salary/benefits in early technical rounds unless they raise it.","g":["n_b_questions","n_b_motivation","b_agile","z_code_review","z_devops","n_b_mentoring"],"cat":"beh"},{"id":"BEH-17","t":"f","l":1,"q":"\"What are your strengths and weaknesses?\"","a":"- Strengths: pick 2-3 that matter for the role, each backed by a short real example (e.g. debugging under pressure in the field, turning manual work into tools, clear technical writing).\n- Weakness: a real one that does not disqualify you for the job, plus what you are actively doing about it and evidence of progress.\n- Avoid fake weaknesses ('I work too hard') and avoid core skills of the role.\n- Keep it under 2 minutes and honest.","g":["n_b_strengths","n_b_learning","n_b_feedback","n_b_career"],"cat":"beh"},{"id":"BEH-18","t":"f","l":1,"q":"\"Where do you see yourself in 3 to 5 years?\"","a":"- Show ambition that fits the company: growing technical depth, owning bigger features or systems, mentoring others.\n- Link it to what this role offers (stack, domain, scale, learning).\n- Avoid: 'in your job', 'starting my own company', or no plan at all.\n- Example shape: 'I want to become a strong backend engineer who can own a service end to end, and later help newer engineers grow.'","g":["n_b_career","n_b_motivation","n_b_learning","n_b_mentoring","z_backend"],"cat":"beh"},{"id":"BEH-19","t":"m","l":1,"q":"What is Agile software development?","o":["Small increments with frequent feedback and change","A programming language built for quick software","A type of database that stores project plans","A long, fixed plan that does not allow changes"],"a":0,"e":"The Agile Manifesto (2001) values: individuals and interactions, working software, customer collaboration and responding to change, over processes, documentation, contracts and plans.\nIn practice: short iterations, regular demos, constant prioritization, close collaboration with the customer, and continuous improvement.\nWaterfall is the opposite style: requirements, design, build, test in strict, long phases.","r":"Agile = small increments, feedback, adapt.","g":["b_agile","b_scrum","b_kanban","b_user_story","b_sprint","z_mvp"],"fa":"An approach that delivers software in small increments with frequent feedback and adapts to changing requirements, instead of planning everything upfront","cat":"beh"},{"id":"BEH-20","t":"m","l":1,"q":"In Scrum, who are the Product Owner, the Scrum Master and the Developers?","o":["PO sets priorities; SM coaches the process; Devs build","The Product Owner writes the code; the SM is boss","The Scrum Master sets priorities; Developers do budgets","They are three types of meetings held in a sprint"],"a":0,"e":"Scrum has three accountabilities:\n- Product Owner: owns the product backlog and decides priorities (value for the customer).\n- Scrum Master: a servant leader who helps the team follow Scrum and removes obstacles; not a manager.\n- Developers: the people doing the work (design, code, test) and who decide how to build it.\nThe whole team is self-organizing.","r":"PO = what and why. Developers = how. SM = process helper.","g":["b_scrum","b_sprint","b_user_story","b_dod","b_retro","z_stakeholder"],"fa":"Product Owner: decides what to build and its priority. Scrum Master: coaches the team on the process and removes blockers. Developers: build the product increment","cat":"beh"},{"id":"BEH-21","t":"m","l":1,"q":"Which Scrum events exist?","o":["Sprint Planning, Daily Scrum, Review and Retrospective","Build, Test and Deploy, run in a fixed order","Kick-off, Audit and Release, held once per quarter","Standup, Lunch and Review, held each day at noon"],"a":0,"e":"A sprint is a fixed period (1 to 4 weeks) that produces a usable increment.\n- Sprint Planning: choose what to do this sprint and how.\n- Daily Scrum: 15-minute sync: progress, plan, blockers.\n- Sprint Review: show the finished work to stakeholders and get feedback.\n- Sprint Retrospective: the team discusses what went well and what to improve.\nArtifacts: product backlog, sprint backlog, increment.","r":"Planning, daily, review, retrospective inside a sprint.","g":["b_scrum","b_sprint","b_retro","z_stakeholder","n_b_feedback"],"fa":"Sprint, Sprint Planning, Daily Scrum (stand-up), Sprint Review, Sprint Retrospective","cat":"beh"},{"id":"BEH-22","t":"m","l":1,"q":"What is a user story and what are acceptance criteria?","o":["A user-view feature description, plus done criteria","A bug report with steps to reproduce the problem","A database table with the records of the users","A commit message with a short summary of a feature"],"a":0,"e":"A user story captures a need, not a technical solution: \"As a customer, I want to reset my password so that I can regain access.\"\nAcceptance criteria are testable conditions: the link expires after 1 hour; an unknown email shows a generic message. A common format is Given/When/Then.\nStories are small enough to finish within a sprint and are estimated by the team (often with story points).","r":"Story = who, what, why. Acceptance criteria = how we know it's done.","g":["b_user_story","b_dod","b_story_points","z_mvp","b_agile","z_stakeholder"],"fa":"A short description of a feature from the user's view (\"As a [user], I want [goal], so that [benefit]\") with acceptance criteria defining when it is done","cat":"beh"},{"id":"BEH-23","t":"m","l":2,"q":"What are story points and velocity?","o":["Points are relative effort; velocity, points per sprint","Story points measure salary; velocity measures typing","Story points are bugs; velocity is a server metric","Both of them measure the lines of code written"],"a":0,"e":"Estimating in hours is often wrong. Teams compare stories to each other: a 5 is roughly 2.5 times a 2. Sizes often follow Fibonacci (1, 2, 3, 5, 8, 13).\nVelocity is the average number of points finished per sprint. It helps forecast how much fits in the next sprint or when a backlog could finish.\nIt is for planning, not for judging individuals or comparing teams.","r":"Points = relative size. Velocity = points per sprint, for forecasting.","g":["b_story_points","b_scrum","b_user_story","b_dod","b_kanban","b_sprint"],"fa":"Story points are a relative estimate of effort/complexity; velocity is how many points a team completes per sprint, used to forecast","cat":"beh"},{"id":"BEH-24","t":"m","l":2,"q":"What is a \"Definition of Done\" (DoD)?","o":["A shared checklist an item must meet to be complete","The date on which the sprint ends for the team","The list of all the known bugs in the backlog","The vision statement of the product for the year"],"a":0,"e":"Without a shared definition, \"done\" means different things to different people. The DoD makes quality explicit: code merged after review, unit and integration tests green, no critical security findings, documentation updated, deployed to a test environment, accepted by the Product Owner.\nAcceptance criteria are per story; the DoD applies to all stories.","r":"DoD = team-wide quality checklist for every item.","g":["b_dod","b_user_story","unit_test","ci","b_sprint","b_agile"],"fa":"A shared checklist of conditions every item must meet to be considered complete (e.g. code reviewed, tests passing, documented, deployed to staging)","cat":"beh"},{"id":"BEH-25","t":"m","l":2,"q":"How does Kanban differ from Scrum?","o":["Kanban limits WIP and flows; Scrum uses sprints","They are identical in the way that they work","Kanban has fixed sprints, while Scrum does not","Kanban is only used for hardware engineering"],"a":0,"e":"Kanban columns show states (To do, In progress, Review, Done). The key rule is WIP limits: a maximum number of items in each column, so you finish work before starting new work, exposing bottlenecks.\nNo mandatory sprint or roles; changes can be added any time. Metrics: lead time and cycle time.\nSupport and maintenance teams often prefer Kanban; product teams often use Scrum. Many teams mix them (\"Scrumban\").","r":"Kanban = continuous flow + WIP limits. Scrum = timeboxed sprints.","g":["b_kanban","b_sprint","b_scrum","n_wip"],"fa":"Kanban uses a visual board, limits work in progress (WIP) and flows continuously without fixed sprints; Scrum works in timeboxed sprints with defined roles and events","cat":"beh"},{"id":"BEH-26","t":"m","l":2,"q":"What is the purpose of a sprint retrospective?","o":["The team reviews its way of working and improves","A demo of the finished product for the customers","An estimation session for the items of the backlog","A meeting to decide who is to blame for bugs"],"a":0,"e":"The retrospective happens at the end of a sprint, after the review. Common format: what went well, what did not, what we will change. The team picks one or two actionable improvements and follows up on them next time.\nIt should be blameless and safe: the aim is improving the system, not criticizing people.","r":"Retro = inspect the process, pick actions, no blame.","g":["b_retro","b_scrum","b_agile","postmortem","n_b_feedback","b_sprint"],"fa":"The team inspects how it worked (process, tools, collaboration) and agrees on concrete improvements for the next sprint","cat":"beh"},{"id":"BEH-27","t":"f","l":2,"q":"How do you explain a technical problem or decision to a non-technical person (written and oral English)?","a":"- Start with the outcome and why it matters to them (impact, risk, cost, time), not with technology names.\n- Use plain words and a simple analogy; define any unavoidable term once.\n- Give 2 or 3 options with trade-offs and your recommendation.\n- Be specific and honest about uncertainty: what you know, what you do not, and when you will know.\n- In writing: short paragraphs, bullet points, a clear subject line, an explicit request (\"I need a decision by Friday\").\n- Check understanding: ask them to restate the key point and invite questions.","g":["n_b_comm","z_stakeholder","n_b_teamwork","n_b_ownership"],"cat":"beh"},{"id":"BEH-28","t":"f","l":2,"q":"Describe how you work in a team and keep a positive attitude under pressure.","a":"- Communicate early and clearly: share progress and blockers in stand-ups, ask for help quickly.\n- Be reliable: finish what you commit to, flag risks before they become surprises.\n- Give and receive code review kindly: comment on the code, not the person; assume good intent.\n- Share knowledge: documentation, pairing, small demos.\n- Under pressure: stay calm, break the problem down, focus on what you can control, and look for the next useful step.\n- Disagreement: listen first, bring data, commit to the team decision.\n- Always back each point with a short real example (STAR).","g":["n_b_teamwork","n_b_conflict","n_b_comm","n_b_feedback","n_star"],"cat":"beh"},{"id":"BEH-29","t":"f","l":3,"q":"Tell me about a complex feature you designed and developed. How do you structure the answer?","a":"- Context (Situation): the problem, the users and why it was hard (scale, deadlines, unknowns).\n- Your role (Task): what you owned, team size, constraints.\n- Design (Action): requirements gathered, options considered with trade-offs, the data model and API you chose, how you split the work in small steps, risks and how you reduced them (prototype, feature flag, tests).\n- Delivery: testing strategy, monitoring, rollout, how you handled changes.\n- Result: measurable outcome (time saved, errors reduced, adoption) and what you would do differently.\n- Use your own real examples; if experience is in another language or domain, say so and explain what transfers.","g":["n_b_ownership","n_b_impact","z_system_design","z_trade_off","microservices","feature_flag","n_b_deadline","api"],"cat":"beh"},{"id":"BEH-30","t":"f","l":2,"q":"How do you approach an unfamiliar problem analytically (problem-solving)?","a":"- Understand: restate the problem, clarify inputs, outputs, constraints and edge cases; ask questions.\n- Reproduce or measure: get facts (logs, a failing test, numbers) before guessing.\n- Break it down: split into smaller parts; solve the simplest part first.\n- Form hypotheses and test them one at a time, cheapest first; change one thing per experiment.\n- Consider options and trade-offs (time, risk, maintainability) before choosing.\n- Verify: tests, edge cases, review; document what you learned.\n- Communicate your thinking aloud in interviews, even when stuck.","g":["n_b_ambiguity","z_trade_off","z_bug","n_b_learning","edge_case","n_b_comm"],"cat":"beh"},{"id":"BEH-31","t":"f","l":1,"q":"The job asks for 5+ years of Java and you are strongest in another language. How do you answer honestly and positively?","a":"- Be honest: state your real Java level and what you have actually built, without exaggerating.\n- Show transferable depth: design patterns, SOLID, SQL, REST APIs, testing, Git, CI/CD, debugging and problem solving are language-independent.\n- Show evidence of learning fast: a Java/Spring project you built, courses, a concrete example of picking up a new technology quickly.\n- Map concepts you know to Java ones (decorators and annotations, pytest and JUnit, FastAPI and Spring Boot, pip and Maven).\n- Say how you would ramp up in the first 3 months and invite a technical exercise.\n- Avoid apologizing; keep a confident, curious tone.","g":["z_java","design_pattern","sp_spring_boot","decorator","z_annotation","pytest","solid","v_maven"],"cat":"beh"},{"id":"BEH-32","t":"m","l":0,"q":"What is a behavioral interview question?","o":["A question about how you acted in a past situation","A coding puzzle that is solved on a whiteboard","A question about your hobbies and free time only","A trick question that has no real answer at all"],"a":0,"e":"Typical starts: 'Tell me about a time when...' (a disagreement, a mistake, a tight deadline).\nInterviewers want evidence of teamwork, communication, ownership and learning. The STAR structure helps: Situation, Task, Action, Result.\nPrepare 6 to 8 real stories you can adapt.","r":"Behavioral = tell a real story of what you did.","g":["z_behavioral","n_b_ownership","n_b_impact","n_b_conflict","n_b_teamwork","n_b_deadline"],"fa":"A question about how you acted in real past situations, used to predict how you will behave at work","cat":"beh"},{"id":"BEH-33","t":"m","l":0,"q":"What does a DevOps engineer mainly work on?","o":["Automating how software is built, deployed and run","Designing the logos and the screens of the app","Writing legal contracts for the clients only","Selling the product to the customers of the firm"],"a":0,"e":"Common roles in a software team:\n- Software/backend/frontend engineer: writes the application code.\n- QA engineer: tests and improves quality.\n- DevOps / platform engineer: pipelines (CI/CD), infrastructure, containers, cloud, monitoring.\n- Product manager / product owner: decides what to build and in what order.\n- Designer (UX/UI): designs how the product looks and feels.","r":"DevOps = build, deploy and run software reliably.","g":["z_devops","ci","cd","z_monitoring","z_frontend","z_backend"],"fa":"Automating how software is built, deployed, run and monitored, so teams can release faster and more reliably","cat":"beh"},{"id":"BEH-34","t":"m","l":0,"q":"What is a ticket (or issue) in tools such as Jira?","o":["A record of one piece of work with owner and status","A parking ticket that is issued by the city","An invoice that is sent to a customer monthly","A password reset email that is sent to the user"],"a":0,"e":"Teams track work in an issue tracker (Jira, GitHub Issues, ClickUp). Each ticket says what has to be done, who does it, and where it is: To Do, In Progress, In Review, Done.\nGood tickets have a clear title, a description, and acceptance criteria.\nCommit messages and pull requests often mention the ticket number, so the history is easy to follow.","r":"Ticket = one tracked piece of work.","g":["z_ticket","b_user_story","v_pull_request","git_commit"],"fa":"A record that describes one piece of work (a bug, task or story) with owner, status and priority","cat":"beh"},{"id":"BEH-35","t":"m","l":0,"q":"What is a stakeholder?","o":["Anyone affected by or interested in the project","Only the person who owns the project servers","A wooden post that is used to mark a place","The compiler that builds the project's code"],"a":0,"e":"Stakeholders are the people who care about the result or are impacted by it. Their needs sometimes conflict.\nIn interview stories (for example 'a difficult stakeholder'), show that you listened, explained technical limits in plain words, and found a solution that served the real need.","r":"Stakeholder = anyone with an interest in the outcome.","g":["z_stakeholder","b_agile","b_scrum","n_b_comm","z_mvp"],"fa":"Anyone affected by or interested in the project: users, customers, managers, other teams","cat":"beh"},{"id":"BEH-36","t":"m","l":0,"q":"What is an MVP?","o":["Minimum Viable Product: the smallest useful version","Most Valuable Programmer on the engineering team","Maximum Value Plan for the budget of the year","Main Visual Page of the website of a company"],"a":0,"e":"Instead of building everything for months, a team ships a small but usable version first, watches how people use it, and then improves it.\nIt reduces the risk of building something nobody wants.\nIn an interview, 'I started with an MVP and iterated' is a good way to describe handling vague requirements.","r":"MVP = smallest useful version, then iterate.","g":["z_mvp","b_agile","b_user_story","b_sprint","z_stakeholder","z_trade_off"],"fa":"Minimum Viable Product: the smallest version that delivers real value and lets you learn from users","cat":"beh"},{"id":"BEH-37","t":"m","l":0,"q":"Which of these is one of the four values of the Agile Manifesto?","o":["Working software over comprehensive documentation","Comprehensive documentation over working software","Following a plan over responding to change","Processes and tools over individuals and interactions"],"a":0,"e":"The Agile Manifesto (2001) values:\n- Individuals and interactions over processes and tools\n- Working software over comprehensive documentation\n- Customer collaboration over contract negotiation\n- Responding to change over following a plan\nIt says that there is value in the items on the right, but the items on the left are valued more. Scrum and Kanban are ways of working inspired by it.","r":"Agile values people, working software, collaboration and change.","g":["b_agile","b_user_story","b_sprint","z_mvp","n_b_teamwork","b_kanban"],"cat":"beh"},{"id":"BEH-38","t":"m","l":0,"q":"What is Kanban?","o":["A visual board workflow that limits work in progress","A fixed two-week planning meeting for the team","A programming language used for task automation","A kind of database that stores project tasks"],"a":0,"e":"A Kanban board shows each work item as a card moving through columns. WIP limits (work in progress) cap how many cards each column may hold, which reduces multitasking and reveals where work piles up.\nKanban comes from Toyota's production system. Unlike Scrum, it focuses on continuous flow, without fixed sprints.","r":"Kanban = board + WIP limits + continuous flow.","g":["b_kanban","n_wip","b_sprint","b_scrum"],"fa":"A visual workflow method that uses a board (To Do, In Progress, Done) and limits the amount of work in progress","cat":"beh"},{"id":"BEH-39","t":"m","l":0,"q":"What is a daily stand-up (Daily Scrum)?","o":["A short daily meeting (15 min) to sync and plan","A weekly one-hour report given to executives","A sports activity that the team does at lunch","A code review session held at the end of each day"],"a":0,"e":"The Scrum Guide describes the Daily Scrum as a 15-minute event for the Developers of the team. It is held every working day at the same time and place.\nCommon questions: what did I do, what will I do next, what blocks me?\nIts purpose is to inspect progress toward the Sprint Goal and adapt the plan, not to report to a manager.","r":"Daily Scrum = 15 minutes, every day, team sync.","g":["b_scrum","b_sprint","b_kanban","b_retro","n_b_comm","b_dod"],"fa":"A short meeting every day (15 minutes in Scrum) where the team syncs on progress and plans the next 24 hours","cat":"beh"},{"id":"BEH-40","t":"f","l":0,"q":"The interviewer asks about something you have not used. How do you answer honestly and well?","a":"- Be honest: say clearly what you have not used. Do not invent experience.\n- Show the nearest thing you know: 'I haven't used Kubernetes in production, but I have used Docker and understand containers, images and ports.'\n- Explain the concept as far as you know it, in simple words.\n- Say how you would learn it: official docs, a small project, asking teammates. Give an example of learning something quickly before.\n- Stay calm and positive; ending with a curious question works well.","g":["z_behavioral","kubernetes","container","port"],"cat":"beh"}],"glossary":{"aaa":["Arrange-Act-Assert","A test structure: prepare (arrange), perform the action (act), check the result (assert)."],"abc":["ABC (Abstract Base Class)","A base class that cannot be instantiated and forces subclasses to implement certain methods (marked with `@abstractmethod`)."],"abstraction":["Abstraction","Showing only what is essential and hiding the details. You drive a car with a wheel and pedals without knowing how the engine works."],"access_control":["Access control","The rules and checks that decide who can see or change which data and features."],"accessibility":["Accessibility (a11y)","Making apps usable by everyone, including people using keyboards, screen readers or with visual impairments."],"acid":["ACID","Four transaction guarantees: Atomicity (all or nothing), Consistency (rules hold), Isolation (no interference), Durability (committed data survives crashes)."],"adapter":["Adapter pattern","A wrapper that converts one interface into another that your code expects, like a travel plug adapter."],"adjacency_list":["Adjacency list","A graph representation where each node maps to a list of its neighbors: `{\"A\": [\"B\", \"C\"]}`."],"aggregate":["Aggregate function","A function that summarizes many rows into one value: COUNT, SUM, AVG, MIN, MAX."],"amortized":["Amortized cost","The average cost per operation over a long sequence, when rare expensive operations are balanced by many cheap ones."],"api":["API","Application Programming Interface: the set of operations a system exposes for other programs, and the format to use them. A web API is used over HTTP."],"api_gateway":["API gateway","A single entry point in front of backend services that handles routing, authentication, rate limiting and TLS."],"array":["Array","Items stored next to each other in memory, accessed by index in O(1). A Python list is a dynamic array that grows automatically."],"arrow_function":["Arrow function","Short JS function syntax: `x => x * 2`. It does not have its own `this`."],"assertion":["Assertion","A statement in a test that checks a condition; if it is false, the test fails."],"asymmetric":["Asymmetric cryptography","Uses a key pair: a public key (shareable) and a private key (secret). Used for key exchange and digital signatures (RSA, ECDSA)."],"async_await":["async / await","`async def` defines a function that can pause. `await` pauses it until a slow operation finishes, letting other tasks run meanwhile."],"attribute":["Attribute","A value stored on an object and accessed with a dot: `user.name`. Methods are attributes too."],"authn":["Authentication","Verifying who a user or system is (password, token, MFA)."],"authz":["Authorization","Deciding what an authenticated user is allowed to do or access."],"autoscaling":["Autoscaling","Automatically adding or removing instances or Pods based on load."],"autospec":["autospec","An option for mocks to copy the real object's method signatures, so invalid calls fail in tests."],"availability":["Availability","The share of time a system is up and answering requests, often written as 'nines' (99.9%)."],"availability_zone":["Availability Zone","An isolated data center (or group) within a cloud region, with independent power and network."],"b_agile":["Agile","A way of building software in short iterations with frequent feedback, valuing working software and responding to change over rigid plans."],"b_dod":["Definition of Done","A team-wide checklist of quality conditions that every work item must meet to count as complete."],"b_kanban":["Kanban","A visual board method with limits on work in progress and continuous flow, instead of fixed sprints."],"b_retro":["Retrospective","A regular, blameless team meeting to review how the team worked and agree on concrete improvements."],"b_scrum":["Scrum","An Agile framework with fixed sprints, three roles (Product Owner, Scrum Master, Developers) and events (planning, daily, review, retrospective)."],"b_sprint":["Sprint","A fixed period (1 to 4 weeks) in Scrum after which the team delivers a usable increment."],"b_story_points":["Story points / velocity","Story points are relative effort estimates; velocity is the number of points a team completes per sprint, used for forecasting."],"b_tree":["B-tree","The balanced tree structure most database indexes use. It keeps values sorted so lookups, ranges and sorting take about log(n) steps."],"b_user_story":["User story","A short description of a need from the user's view: \"As a ..., I want ..., so that ...\", with acceptance criteria to confirm it is done."],"background_job":["Background job","Work that runs outside the request/response cycle, in a separate worker process, e.g. sending emails or building reports."],"backtracking":["Backtracking","Exploring all candidate solutions by making a choice, recursing, then undoing the choice and trying the next one."],"base_case":["Base case","The simplest input of a recursive function, answered directly without another recursive call. It stops the recursion."],"bfs":["BFS (breadth-first search)","Exploring a graph level by level using a queue: all nodes 1 step away, then 2 steps, etc. Finds shortest paths in unweighted graphs."],"big_o":["Big-O notation","A way to describe how an algorithm's time or memory grows as the input size n grows, ignoring constants: O(1), O(log n), O(n), O(n log n), O(n²)."],"binary_search":["Binary search","Finding an item in a SORTED list by repeatedly checking the middle and discarding half. O(log n)."],"bit_manipulation":["Bit manipulation","Working directly with the binary digits of numbers using operators like & (and), | (or), ^ (xor), << and >> (shifts)."],"blocking":["Blocking call","A call that makes the thread wait and do nothing else until it finishes, like `time.sleep()` or `requests.get()`. Inside async code it freezes everything."],"blue_green":["Blue-green deployment","Two identical environments; deploy to the idle one, then switch all traffic to it at once. Easy rollback."],"box_model":["CSS box model","Every element is a box made of content, padding, border and margin. `box-sizing` decides whether width includes padding and border."],"broker":["Message broker","The server software that receives, stores and delivers messages between services (RabbitMQ, Kafka, SQS)."],"brute_force":["Brute-force attack","Trying huge numbers of possible passwords or keys until one works."],"bst":["Binary search tree (BST)","A tree where each node has up to two children, all smaller keys on the left and bigger keys on the right. Fast search if balanced."],"builder":["Builder","A pattern that constructs a complex object step by step: `Request().url(u).header(h).timeout(5).build()`."],"cache":["Cache","A fast storage layer (usually memory) holding copies of data that is expensive to fetch or compute."],"cache_aside":["Cache-aside","The app checks the cache first; on a miss it loads from the database and saves the result in the cache."],"cache_stampede":["Cache stampede","Many requests miss the cache at the same moment (often when a hot key expires) and all hit the database together."],"call_stack":["Call stack","The memory area that keeps track of active function calls. Each call adds a frame; returning removes it. Too many nested calls → stack overflow / RecursionError."],"callback":["Callback","A function you pass to other code so it can call it later, e.g. when a click happens or data arrives."],"canary":["Canary release","Sending a small percentage of traffic to a new version first, watching metrics, then increasing gradually."],"cap":["CAP theorem","In a distributed system, during a network partition you must choose between Consistency (everyone sees the latest data) and Availability (every request gets an answer)."],"cd":["Continuous Delivery / Deployment","Automating the release process so changes can go (Delivery, with approval) or do go (Deployment, automatically) to production."],"cdn":["CDN","Content Delivery Network: servers around the world that cache static content close to users."],"certificate":["TLS certificate","A digital document, signed by a trusted authority, that proves a public key belongs to a specific domain."],"ci":["Continuous Integration","Automatically building and testing every code change pushed to the shared repository."],"circuit_breaker":["Circuit breaker","A pattern that stops calling a failing service for a while after repeated errors, failing fast instead of waiting for timeouts."],"class":["Class","A blueprint that defines what data (attributes) and behavior (methods) its objects have."],"client_server":["Client-server model","Clients (browsers, apps) send requests over the network; servers process them and send responses."],"closure":["Closure","A function that remembers variables from the place where it was created, even after that outer function has finished. It remembers the variable itself, not a frozen copy of its value."],"cloud":["Cloud computing","Renting computing resources and managed services from a provider (AWS, Azure, GCP) on demand over the internet."],"code_smell":["Code smell","A sign in the code that suggests a deeper design problem: huge classes, long functions, duplicated logic, too many parameters."],"coercion":["Type coercion","Automatic conversion of a value from one type to another, e.g. JavaScript turning \"5\" into 5 when comparing with ==."],"cohesion":["Cohesion","How closely the parts inside a module belong together. High cohesion = a focused module with one clear purpose."],"collision":["Hash collision","When two different keys produce the same slot in a hash table. Handled by chaining or probing; too many slow things down."],"component":["Component","A reusable, self-contained piece of UI. In React, a function that receives props and returns JSX."],"composite_index":["Composite index","An index on several columns in a specific order, e.g. (last_name, first_name). Useful only when queries filter on its leftmost columns."],"composition":["Composition","Building an object from other objects it holds as attributes ('has-a'): a Car has an Engine."],"concurrency":["Concurrency vs parallelism","Concurrency: handling several tasks in overlapping time by switching between them (one cook, many pots). Parallelism: literally running at the same instant on several CPU cores (many cooks)."],"conftest":["conftest.py","A pytest file whose fixtures are automatically available to all tests in its folder and subfolders."],"connection_pool":["Connection pool","A set of already-open database connections that the app borrows and returns, instead of opening a new one for each query."],"consistency":["Consistency (distributed)","Every read sees the most recent write, no matter which server answers."],"consistent_hashing":["Consistent hashing","A way to assign keys to servers on a 'ring' so that adding or removing a server moves only a small fraction of keys."],"container":["Container","A lightweight, isolated process packaged with its app and dependencies, sharing the host's operating system kernel."],"context_manager":["Context manager","An object used with `with` that runs setup code at the start and cleanup code at the end, even if an error occurs. Files, locks and DB transactions use it."],"contract_test":["Contract test","A test that checks a service's API still matches what its consumers expect."],"controlled_input":["Controlled input","A form input whose value comes from React state and is updated through onChange."],"cookie":["Cookie","A small piece of data a server asks the browser to store and send back automatically on every request to that site. Often used for sessions."],"core_web_vitals":["Core Web Vitals","Google's user-experience metrics: LCP (loading), INP (responsiveness), CLS (visual stability)."],"coroutine":["Coroutine","The object created by calling an `async def` function. It is a pausable piece of work that only runs when awaited or scheduled."],"cors":["CORS","Cross-Origin Resource Sharing: headers by which a server tells browsers which other websites (origins) may read its responses."],"coupling":["Coupling","How much one module depends on the internals of another. Low coupling = you can change one without breaking the other."],"coverage":["Test coverage","The percentage of code lines or branches executed by the test suite."],"cpu_bound":["CPU-bound","Work that spends its time calculating (image processing, math loops, compression). It is limited by processor speed, not by waiting."],"cqrs":["CQRS","Command Query Responsibility Segregation: separate models (and often stores) for writing data and for reading it."],"credential_stuffing":["Credential stuffing","Automatically trying username/password pairs leaked from other sites, exploiting password reuse."],"csp":["Content-Security-Policy","An HTTP header listing which sources the browser may load scripts, styles and other content from."],"csrf":["CSRF (Cross-Site Request Forgery)","A malicious site makes the victim's browser send a request to another site where they are logged in, using their cookies."],"css":["CSS","Cascading Style Sheets: rules that control how HTML looks (colors, fonts, spacing, layout)."],"cve":["CVE","Common Vulnerabilities and Exposures: a public ID (e.g. CVE-2024-1234) for a known security flaw in software."],"d_abstract_factory":["Abstract Factory","A pattern with an interface that creates families of related objects without naming their concrete classes."],"d_chain":["Chain of Responsibility","A request passes through a sequence of handlers; each may process it or pass it on. Servlet filters work this way."],"d_composite":["Composite","A tree structure where individual items and groups share one interface, like files and folders."],"d_covering_index":["Covering index","An index containing all columns a query needs, so the database can answer without reading the table."],"d_cte":["CTE (Common Table Expression)","A named temporary result defined with `WITH` that makes complex queries easier to read; can be recursive."],"d_dao":["DAO (Data Access Object)","A class that hides how a particular table or entity is stored and retrieved, usually with CRUD methods."],"d_ddl_dml":["DDL / DML","DDL (CREATE, ALTER, DROP) defines structure. DML (INSERT, UPDATE, DELETE) changes data."],"d_decorator":["Decorator","A wrapper with the same interface as the wrapped object that adds behavior, such as `BufferedReader` wrapping `FileReader`."],"d_enum_singleton":["Enum singleton","Implementing a Singleton as a single-value Java enum; the JVM guarantees exactly one instance and it is thread-safe."],"d_exists":["EXISTS / NOT EXISTS","A SQL test that is true if a subquery returns at least one row (EXISTS) or none (NOT EXISTS)."],"d_flyweight":["Flyweight","Saves memory by sharing identical immutable objects, like the Integer cache and the string pool."],"d_god_object":["God object","An anti-pattern: one huge class that knows and does too much. Split it by responsibility."],"d_gof":["GoF (Gang of Four)","The four authors of the book \"Design Patterns\" (1994), which catalogued 23 classic object-oriented design patterns."],"d_junction":["Junction table","A table with two foreign keys that links two tables in a many-to-many relationship."],"d_mvc":["MVC","Model-View-Controller: separates data and rules (model), presentation (view) and request handling (controller)."],"d_normal_forms":["Normal forms (1NF, 2NF, 3NF)","Progressive rules for table design that remove redundancy: atomic values (1NF), full dependence on the key (2NF), no dependence between non-key columns (3NF)."],"d_proxy":["Proxy pattern","An object that stands in for another with the same interface to control access or add behavior (transactions, caching, lazy loading)."],"d_relational":["Relational database","A database that stores data in tables with rows and columns, linked by keys, and queried with SQL (PostgreSQL, MySQL, Oracle, SQL Server)."],"d_surrogate_key":["Surrogate key","An artificial identifier (auto-increment id or UUID) with no business meaning, used as a stable primary key."],"d_template_method":["Template Method","A base class fixes the steps of an algorithm and lets subclasses supply specific steps."],"d_view":["View","A named, saved query that behaves like a virtual table. A materialized view stores its result physically."],"dag":["DAG","Directed Acyclic Graph: a graph with one-way edges and no cycles. Dependency graphs are DAGs."],"dataclass":["Dataclass","A class decorated with `@dataclass` that automatically gets `__init__`, `__repr__` and `__eq__` from its declared fields. Great for plain data objects."],"deadlock":["Deadlock","Two or more transactions each wait for a lock the other holds, so none can continue. The database aborts one of them."],"debounce":["Debounce","Delaying a function until events stop for a given time, so it runs once after a burst (e.g. typing)."],"decorator":["Decorator","A function that takes another function and returns a modified version of it. `@timer` above `def f` means `f = timer(f)`. Used for logging, caching, permissions, retries."],"deep_copy":["Deep copy","A completely independent copy, including copies of all nested objects: `copy.deepcopy(a)`."],"default_arg":["Default argument","A value used when the caller does not pass that parameter: `def f(x=10)`. In Python it is created once, when the function is defined."],"defer_async":["defer / async scripts","Script attributes that download JS without blocking HTML parsing. defer keeps order and waits for parsing; async runs as soon as ready."],"delivery_semantics":["Delivery guarantees","At-most-once (may lose messages), at-least-once (may duplicate), exactly-once (hard; usually achieved with idempotent processing)."],"denormalization":["Denormalization","Intentionally duplicating some data to make reads faster, at the cost of more complex writes."],"dependency":["Dependency","An external library your code needs, such as requests or Django. Versions are usually pinned in requirements.txt, pyproject.toml or a lock file."],"dependency_injection":["Dependency injection","Giving an object the things it needs (database, API client, clock) from outside, usually via the constructor, instead of creating them inside."],"deployment_k8s":["Deployment (Kubernetes)","An object that keeps a desired number of identical Pods running and handles rolling updates and rollbacks."],"deque":["deque","'Double-ended queue' from `collections`. Fast O(1) add/remove at both ends; ideal for queues."],"descriptor":["Descriptor","An object that customizes attribute access by defining `__get__`, `__set__` or `__delete__`. Properties and methods are built on it."],"design_pattern":["Design pattern","A named, proven solution to a recurring design problem (Factory, Strategy, Observer...). An idea to adapt, not a library."],"deterministic":["Deterministic","Always producing the same output for the same input, with no dependence on time, randomness or order."],"dfs":["DFS (depth-first search)","Exploring a graph by going as deep as possible along one path before backtracking, using recursion or a stack."],"dict":["Dictionary (dict)","A collection of key → value pairs with fast lookup by key: `{\"name\": \"Ana\"}`. Keys must be hashable."],"dijkstra":["Dijkstra's algorithm","Finds the shortest path from one node to all others in a graph with non-negative edge weights, using a min-heap."],"dip":["Dependency Inversion Principle","High-level business code should depend on abstractions (interfaces), not on concrete low-level details."],"dns":["DNS","Domain Name System: translates human-readable domain names into IP addresses."],"docker_compose":["Docker Compose","A tool to define and run several containers together from one YAML file."],"docker_image":["Docker image","A read-only, layered template containing an app and everything it needs to run. Containers are started from images."],"dockerfile":["Dockerfile","A text file with instructions (FROM, COPY, RUN, CMD...) that Docker follows to build an image."],"dom":["DOM","Document Object Model: the tree of objects the browser builds from HTML. JavaScript reads and changes it to update the page."],"dp":["Dynamic programming","Solving a problem by breaking it into overlapping subproblems and storing each subproblem's answer so it is computed only once."],"duck_typing":["Duck typing","'If it walks like a duck and quacks like a duck, it is a duck.' Code cares about what an object can do (its methods), not its class."],"dunder":["Dunder method","'Double underscore' methods like `__init__`, `__eq__`, `__len__`. Python calls them automatically for built-in behavior (creation, comparison, len(), printing)."],"e2e_test":["End-to-end test","A test that exercises the whole system from the user's point of view, e.g. a browser clicking through the app."],"edge_case":["Edge case","An unusual or extreme input at the boundary of what a function handles: empty, zero, max size, None."],"encapsulation":["Encapsulation","Keeping data and the methods that use it together and hiding internal details, so other code uses only a safe public interface."],"encoding":["Encoding vs encryption","Encoding (base64, UTF-8) only changes the representation; anyone can reverse it. Encryption needs a key to read the data."],"encryption":["Encryption","Scrambling data so only someone with the right key can read it. Reversible with the key, unlike hashing."],"endpoint":["Endpoint","One specific URL + HTTP method your API handles, e.g. `GET /users/{id}`, usually mapped to one function."],"env_var":["Environment variable","A named value provided to a program by its environment (`os.environ[\"KEY\"]`), commonly used for configuration and secrets."],"etag":["ETag","A version identifier for a resource sent by the server. Lets clients ask 'has it changed?' and get 304 Not Modified if not."],"event_bubbling":["Event bubbling","An event on an element also triggers on its parent, then its parent's parent, up to the document."],"event_delegation":["Event delegation","Handling events of many child elements with one listener on their common parent, thanks to bubbling."],"event_loop":["Event loop","The engine of asyncio. It runs many tasks in one thread, switching to another task whenever the current one is waiting (at an `await`)."],"event_loop_js":["JavaScript event loop","The mechanism that runs JS on a single thread: run synchronous code, then all microtasks (promises), then the next macrotask (timers, events)."],"eventual_consistency":["Eventual consistency","Copies of data may differ for a short time after a write, but will all become the same if no new writes arrive."],"exception":["Exception","An error object raised while the program runs (ValueError, KeyError...). If nobody catches it with try/except, the program stops and shows a traceback."],"exit_code":["Exit code","A number a process returns when it ends: 0 means success, anything else means an error or a signal."],"explain":["EXPLAIN","A SQL command that shows how the database plans to run a query (indexes used, scans, joins). EXPLAIN ANALYZE also runs it and shows real timings."],"f_array_methods":["map / filter / reduce","Array methods that return new results: map transforms each item, filter keeps matching items, reduce combines items into one value."],"f_bundler":["Bundler (Vite, webpack)","A build tool that transpiles, combines and minifies source files into optimized files for the browser, with a hot-reload dev server."],"f_context":["React Context","A way to make a value available to all descendant components without passing props at every level."],"f_npm":["npm / package.json","npm is the Node package manager. `package.json` lists metadata, scripts and dependencies; `npm install` downloads them to `node_modules`."],"f_rtl":["React Testing Library","A library that renders React components in tests and queries them like a user would (by role or text)."],"f_spa":["SPA (Single Page Application)","A web app that loads once and updates the view with JavaScript and API calls instead of full page reloads."],"facade":["Facade pattern","A simple front-door class that hides a complicated subsystem behind a few easy methods."],"factory":["Factory","A function or class whose job is to create objects, choosing the right concrete type: `create_parser(\"json\")` returns a JsonParser."],"failover":["Failover","Automatically switching to a backup component when the main one fails."],"fake":["Fake","A simple working implementation used in tests instead of the real one, e.g. an in-memory database."],"feature_flag":["Feature flag","A configuration switch that turns a feature on or off at runtime, for all users or some, without redeploying."],"fixture":["Fixture (pytest)","A function that prepares something a test needs (data, connection, client) and optionally cleans it up afterwards."],"flaky_test":["Flaky test","A test that sometimes passes and sometimes fails without any code change."],"flexbox":["Flexbox","A CSS layout model for arranging items in one direction (row or column), with easy alignment and spacing."],"foreign_key":["Foreign key","A column that holds the primary key of a row in another table, creating a relationship the database can enforce."],"function":["Function","A named, reusable block of code. It receives inputs (parameters), does something, and can give back a result with `return`."],"garbage_collector":["Garbage collector","The part of a language runtime that automatically frees memory no longer in use. In Python, the `gc` module mainly cleans up reference cycles."],"generator":["Generator","A function that uses `yield` to produce values one at a time, pausing between them. It does not build the whole result in memory, and it can only be consumed once."],"generic":["Generic type","A type with a placeholder, like `list[T]`, so the same code works for many types while keeping type information."],"gil":["GIL (Global Interpreter Lock)","A lock inside CPython (the standard Python) that allows only one thread to run Python code at a time. It keeps Python's memory management simple and safe, but it means threads cannot do heavy calculations in parallel."],"git_branch":["Branch","An independent line of development in Git. Lets you work on a feature without touching the main code until it is merged."],"git_commit":["Commit","A saved snapshot of changes in a Git repository, with an ID and a message describing the change."],"global_state":["Global state","Data that any part of the program can read and change. It creates hidden connections between code and makes testing harder."],"graph":["Graph","A set of nodes (vertices) connected by edges. Edges can be directed or undirected, weighted or not."],"graphql":["GraphQL","An API query language where the client asks for exactly the fields it needs in one request, through a single endpoint."],"grid":["CSS Grid","A CSS layout model for arranging items in rows and columns at the same time."],"group_by":["GROUP BY","Groups rows that share a value so aggregate functions can be computed per group."],"grpc":["gRPC","A high-performance RPC framework using Protobuf binary messages over HTTP/2, with code generated from a shared schema."],"hash":["Hash","A number calculated from a value, used to find it quickly in sets and dict keys. Equal values must have equal hashes. Only immutable values are normally hashable."],"hash_table":["Hash table","A structure that stores key → value pairs in an array, using a hash of the key to find the slot. Python's dict and set. O(1) average lookup."],"hashing":["Hash function","A one-way function that maps any input to a fixed-size fingerprint. The same input always gives the same output."],"header":["HTTP header","A name: value pair carrying extra information with a request or response, e.g. `Authorization: Bearer <token>` or `Content-Type: application/json`."],"heap":["Heap / priority queue","A tree-based structure that always gives quick access to the smallest (min-heap) or largest item. Python: `heapq`. Push/pop O(log n)."],"high_availability":["High availability","Designing a system to keep working despite failures, using redundancy and automatic failover."],"higher_order":["Higher-order function","A function that receives functions as arguments or returns a function. Decorators, `map` and `sorted(key=...)` are examples."],"hmac":["HMAC","A signature computed from a message and a secret key. Anyone with the key can verify that the message is authentic and unchanged."],"hoisting":["Hoisting","JavaScript's behavior of moving declarations to the top of their scope before running code."],"hook":["React hook","Functions starting with `use` (useState, useEffect, useMemo...) that give function components state and lifecycle features."],"horizontal_scaling":["Horizontal scaling","Adding more servers that share the work, usually behind a load balancer. Requires stateless app design."],"hsts":["HSTS","HTTP Strict Transport Security: a header telling browsers to always use HTTPS for a domain."],"html":["HTML","HyperText Markup Language: the tags that define a web page's structure and content (headings, paragraphs, links, forms)."],"http":["HTTP","The protocol browsers and apps use to talk to web servers: a client sends a request (method, URL, headers, body) and gets a response (status code, headers, body)."],"http2":["HTTP/2","A newer version of HTTP that sends many requests at once over one connection and compresses headers."],"http_method":["HTTP method","The verb of a request: GET (read), POST (create), PUT (replace), PATCH (partial update), DELETE (remove)."],"httponly":["HttpOnly cookie","A cookie flag that hides the cookie from JavaScript, so injected scripts cannot steal it."],"https":["HTTPS","HTTP running inside an encrypted TLS connection. Protects data from being read or changed and verifies the server's identity."],"hydration":["Hydration","Attaching JavaScript behavior to server-rendered HTML in the browser so it becomes interactive."],"iac":["Infrastructure as Code","Defining servers, networks and databases in code files, so infrastructure is versioned, reviewed and reproducible."],"iam":["IAM","Identity and Access Management: the AWS (or other cloud) system for users, roles and permissions."],"idempotent":["Idempotent","An operation that has the same effect whether you do it once or many times. Setting x = 5 is idempotent; adding 1 to x is not."],"identity":["Identity","Which exact object in memory a variable refers to. `id(x)` shows it and `is` compares it. Two equal lists can still be two different objects."],"idor":["IDOR","Insecure Direct Object Reference: accessing someone else's data by changing an ID in the request, because ownership is not checked."],"immutable":["Immutable","An object that cannot change after creation, like int, str, tuple or frozenset. 'Changing' it really creates a new object."],"immutable_infra":["Immutable infrastructure","Replacing servers with freshly built images for every change instead of modifying them in place."],"index":["Index","A sorted lookup structure on one or more columns that lets the database find rows quickly without scanning the whole table."],"inheritance":["Inheritance","A class (child) reuses and extends another class (parent): `class Dog(Animal)`. The child gets the parent's methods and can override them."],"inner_join":["INNER JOIN","Returns only rows that have a match in both tables."],"input_validation":["Input validation","Checking that incoming data matches what is expected (type, length, format, range) and rejecting anything else."],"instance":["Instance","A concrete object created from a class. `rex = Dog()` makes `rex` an instance of Dog. The class is the blueprint; the instance is the house."],"integration_test":["Integration test","A test that checks several real components working together, such as your code with a real database."],"interface":["Interface","The set of methods an object promises to offer, without saying how they work inside. In Python often expressed with an ABC or a Protocol."],"io_bound":["I/O-bound","Work that spends most of its time waiting for input/output: network calls, disk reads, database queries. The CPU is mostly idle while waiting."],"isolation_level":["Isolation level","How much concurrent transactions are protected from each other: Read Uncommitted, Read Committed, Repeatable Read, Serializable."],"isp":["Interface Segregation Principle","Prefer several small, focused interfaces over one large one, so classes implement only what they use."],"iterable":["Iterable","Anything you can loop over with `for`: lists, strings, dicts, files, ranges. Calling `iter()` on it gives an iterator."],"iterator":["Iterator","An object that returns the next item each time you call `next()` on it, and remembers where it is. When it has no more items, it raises StopIteration."],"j_abstract_class":["Abstract class","A class that cannot be instantiated directly. It can hold fields, constructors and ready methods, plus `abstract` methods that subclasses must implement."],"j_access_modifier":["Access modifier","A keyword that controls who can see a class member: public (all), protected (package and subclasses), none (package only), private (same class only)."],"j_arraylist":["ArrayList","A List backed by a resizable array: fast access by index, fast appends, compact memory. The default choice for lists."],"j_atomic":["Atomic classes","`AtomicInteger`, `AtomicLong`... provide thread-safe operations such as `incrementAndGet()` without explicit locks."],"j_autocloseable":["AutoCloseable","An interface with one method, `close()`. Any class implementing it can be used in try-with-resources."],"j_boxing":["Autoboxing / unboxing","Automatic conversion between a primitive and its wrapper object (int to Integer and back). Unboxing a null wrapper throws NullPointerException."],"j_bytecode":["Bytecode","The intermediate, platform-neutral instructions that `javac` produces from your `.java` files (stored in `.class` files). The JVM runs it."],"j_checked_exc":["Checked exception","An exception the compiler forces you to catch or declare with `throws`, such as IOException."],"j_cme":["ConcurrentModificationException","Thrown when a collection is structurally modified while an iterator is walking it (even in one thread). Use removeIf or Iterator.remove instead."],"j_collections":["Collections Framework","Java's built-in set of data structures and interfaces: List, Set, Map, Queue, Deque and their implementations (ArrayList, HashSet, HashMap, ArrayDeque...)."],"j_comparable":["Comparable","An interface with `compareTo` that gives a class its single natural ordering."],"j_comparator":["Comparator","A separate object with `compare(a, b)` defining a custom ordering, e.g. sort people by age or by name."],"j_completable_future":["CompletableFuture","A result that will be available later, with methods to chain steps (`thenApply`, `thenCompose`, `thenCombine`) without blocking."],"j_concurrenthashmap":["ConcurrentHashMap","A thread-safe Map built for many threads at once, with non-blocking reads and fine-grained locking on writes. Offers atomic methods like `merge` and `computeIfAbsent`."],"j_defensive_copy":["Defensive copy","Copying a mutable object when receiving it or returning it, so outsiders cannot change your internal state."],"j_deserialization":["Deserialization attack","Feeding crafted serialized data to an app so rebuilding the objects runs attacker-controlled code (gadget chains)."],"j_equals_hashcode":["equals / hashCode contract","`equals` says whether two objects are logically the same. `hashCode` gives a number used by hash collections. If two objects are equal, they must return the same hashCode."],"j_executor":["ExecutorService","The Java API to submit tasks to a thread pool and get a `Future` with the result."],"j_final":["final","A modifier that prevents change: a final variable is assigned once, a final method cannot be overridden, a final class cannot be extended."],"j_finally":["finally","A block that runs after try/catch no matter what happened, including after a return or an exception. Typically used for cleanup."],"j_gc":["Garbage collector","The JVM component that automatically frees objects that can no longer be reached, so developers do not call `free` manually."],"j_generics":["Generics","Parameterized types such as `List<String>` that let the compiler check element types and remove the need for casts."],"j_hashmap":["HashMap","A Map that finds values by hashing the key into buckets. Average O(1) get and put. Not thread-safe; allows one null key."],"j_heap":["Java heap","The shared memory area where all objects live. It is cleaned by the garbage collector. When it is full: OutOfMemoryError."],"j_immutable_class":["Immutable class","A class whose objects never change after construction (final fields, no setters). Safe to share between threads."],"j_jdk":["JDK / JRE","JRE (Java Runtime Environment) = JVM + standard libraries, enough to run programs. JDK (Java Development Kit) = JRE + developer tools such as the compiler `javac`."],"j_jvm":["JVM (Java Virtual Machine)","The program that loads Java bytecode and executes it, manages memory (garbage collection) and optimizes hot code while running. Each operating system has its own JVM."],"j_lambda":["Lambda expression","A short anonymous function written as `(args) -> expression`, e.g. `n -> n * 2`. It can be used wherever a functional interface is expected."],"j_mem_leak":["Memory leak (Java)","Objects that are still referenced (so the GC cannot free them) but will never be used again, causing the heap to grow."],"j_optional":["Optional","A container that may hold a value or be empty. Used as a return type to make \"might be missing\" explicit instead of returning null."],"j_overload":["Overloading","Several methods with the same name but different parameter lists in the same class. The compiler chooses at compile time."],"j_override":["Overriding","A subclass provides its own implementation of an inherited method with the same signature. The JVM chooses the version at runtime from the real object type."],"j_primitive":["Primitive type","A basic value type built into Java: int, long, double, boolean, char, byte, short, float. It is not an object and can never be null."],"j_record":["Record","A compact immutable data class (Java 16+): `record Point(int x, int y) {}` generates constructor, accessors, equals, hashCode and toString."],"j_runtime_exc":["Unchecked (runtime) exception","An exception extending RuntimeException (NullPointerException, IllegalArgumentException...). The compiler does not force you to handle it; it usually signals a bug."],"j_stack_mem":["Thread stack","A per-thread memory area holding one frame per active method call with its local variables. Too many nested calls cause StackOverflowError."],"j_static":["static","A class-level member: one copy shared by all objects, usable without creating an instance (`Math.max(1, 2)`)."],"j_stream":["Stream API","A way to process collections as a pipeline (filter, map, collect). Streams are lazy: nothing runs until a terminal operation such as `toList()` or `forEach` is called."],"j_string_pool":["String pool","A special memory area where Java keeps one copy of each string literal, so identical literals share the same object."],"j_stringbuilder":["StringBuilder","A mutable text buffer for building strings efficiently. Unlike String, appending to it does not copy the whole text every time."],"j_stw":["Stop-the-world pause","A moment when the JVM pauses all application threads so the garbage collector can work safely. Long pauses cause latency spikes."],"j_synchronized":["synchronized","A keyword that lets only one thread at a time run a block or method for a given lock object, and makes its changes visible to other threads."],"j_thread_pool":["Thread pool","A fixed or bounded group of reusable worker threads that execute queued tasks, avoiding the cost and risk of one thread per task."],"j_try_with_res":["try-with-resources","A try statement that opens resources in parentheses and closes them automatically at the end, even after an exception."],"j_type_erasure":["Type erasure","The compiler removes generic type arguments after checking, so at runtime `List<String>` and `List<Integer>` are both plain `List`."],"j_virtual_thread":["Virtual thread","A lightweight thread (Java 21) scheduled by the JVM instead of the OS. Millions can exist, which suits I/O-heavy servers."],"j_volatile":["volatile","A field modifier guaranteeing that all threads see the latest written value. It does not make compound actions like `count++` atomic."],"javascript":["JavaScript","The programming language that runs in browsers (and on servers with Node.js) to make pages interactive."],"join":["JOIN","Combining rows of two tables based on a related column, e.g. orders.customer_id = customers.id."],"json":["JSON","A text data format with objects `{\"key\": value}` and arrays `[...]`. The standard format for web APIs."],"jwt":["JWT (JSON Web Token)","A compact token with three parts (header.payload.signature). The payload holds claims like user ID and expiry; the signature proves the server issued it."],"k8s_secret":["Kubernetes Secret","An object to hold sensitive values and inject them into Pods. Encoded, not encrypted, by default."],"kadane":["Kadane's algorithm","An O(n) algorithm for the maximum sum of a contiguous subarray: at each element, extend the current run or restart."],"kafka":["Kafka","A distributed event streaming platform: messages are stored in an ordered, replayable log split into partitions."],"keyword_arg":["Keyword argument","An argument passed by name: `f(size=10)`. Order does not matter and calls are easier to read."],"kubernetes":["Kubernetes (K8s)","A system that automates deploying, scaling, healing and networking containers across a cluster of machines."],"lambda":["Lambda","A small anonymous function written in one expression: `lambda x: x * 2` is the same as `def f(x): return x * 2`."],"latency":["Latency","The time one operation takes from start to finish, e.g. how long a request waits for its response."],"layer_cache":["Docker layer cache","Docker reuses the result of each build step if its inputs did not change, which makes rebuilds fast."],"lazy":["Lazy evaluation","Computing values only when they are actually needed, instead of all at once in advance. Saves memory and time when not everything is used."],"leader_follower":["Leader-follower replication","One node (leader) accepts writes and copies them to followers, which serve reads and can replace the leader."],"least_privilege":["Least privilege","Giving every user, service and key only the minimum permissions it needs."],"left_join":["LEFT JOIN","Returns all rows from the left table, plus matching rows from the right one (NULL where there is no match)."],"linear_search":["Linear search","Checking items one by one from the start until the target is found. O(n)."],"linked_list":["Linked list","A sequence of nodes where each node holds a value and a pointer to the next node. Easy to insert/remove; slow to access by index."],"list":["List","An ordered, changeable collection: `[1, 2, 3]`. Items are accessed by position, starting at 0."],"list_comprehension":["List comprehension","A compact way to build a list from a loop: `[x * 2 for x in nums if x > 0]`. With parentheses instead of brackets it becomes a generator expression."],"load_balancer":["Load balancer","A component that spreads incoming requests across several servers and skips unhealthy ones."],"load_test":["Load test","Simulating many concurrent users to measure performance and find the system's limits."],"lock":["Lock (mutex)","A tool that lets only one thread at a time run a protected piece of code: `with lock: ...`. Prevents race conditions."],"logs":["Logs, metrics, traces","Logs: timestamped text events. Metrics: numeric measurements over time. Traces: the timed path of one request through services."],"lru":["LRU cache","A fixed-size cache that removes the Least Recently Used item when it needs space."],"lsp":["Liskov Substitution Principle","A subclass must work anywhere its parent class is expected, without surprising the caller."],"media_query":["Media query","A CSS condition (screen width, dark mode, etc.) that applies rules only when true."],"memoization":["Memoization","Caching a function's results by its arguments, so repeated calls with the same input return instantly. Python: `@functools.lru_cache`."],"merge":["Merge","Combining the changes from one branch into another. Keeps both histories and adds a merge commit when needed."],"merge_sort":["Merge sort","A sort that splits the list in halves, sorts each, and merges them. Always O(n log n), stable, uses extra memory."],"message_queue":["Message queue","A buffer where one service puts messages and another takes them later, so they don't have to be available at the same time."],"metaclass":["Metaclass","The 'class of a class': it creates classes the way classes create objects. The default is `type`. Rarely needed in everyday code."],"metadata":["Metadata","Data about data. For a function: its name (`__name__`), docstring (`__doc__`), module, and so on."],"method":["Method","A function defined inside a class. It receives the object (`self`) automatically as its first argument."],"mfa":["MFA","Multi-factor authentication: requiring two or more different kinds of proof of identity, such as a password plus a phone code."],"microservices":["Microservices","An architecture where an application is split into small, independently deployable services that communicate over the network."],"microtask":["Microtask vs macrotask","Microtasks (promise callbacks) run right after the current code, before any macrotask (setTimeout, I/O, UI events)."],"middleware":["Middleware","Code that runs around every request and response in a web app, for cross-cutting tasks like logging, auth, CORS or timing."],"mock":["Mock","A test double that replaces a real dependency, returns what you configure, and records calls so you can verify them."],"monolith":["Monolith","An application built and deployed as a single unit. Can be well organized internally (modular monolith)."],"monotonic_stack":["Monotonic stack","A stack kept in increasing or decreasing order, used to find the next greater or smaller element for every item in O(n)."],"mro":["MRO (Method Resolution Order)","The order in which Python searches classes for a method or attribute when inheritance is involved. See it with `ClassName.__mro__`."],"multi_stage":["Multi-stage build","A Dockerfile with several FROM stages, where later stages copy only the needed outputs from earlier ones."],"multiple_inheritance":["Multiple inheritance","A class with more than one parent: `class D(B, C)`. Python resolves conflicts using the MRO."],"mutable":["Mutable","An object that can be changed after it is created, like a list, dict or set. If two variables point to the same mutable object, a change through one is visible through the other."],"mutation_testing":["Mutation testing","Planting small bugs in the code to check whether the test suite notices them."],"n_aes":["AES","Advanced Encryption Standard: the standard symmetric cipher. One key encrypts and decrypts. Used by TLS, disk encryption and cloud storage."],"n_aks":["AKS","Azure Kubernetes Service: Microsoft's managed Kubernetes. Azure runs the control plane for you."],"n_alb_nlb":["ALB / NLB","AWS load balancers. ALB works at layer 7 (HTTP) and can route by path or host. NLB works at layer 4 (TCP/UDP) for very high speed."],"n_app_props":["application.yml / application.properties","Spring Boot's main config file: server port, database URL and any custom settings. Profiles can override it for each environment."],"n_arraydeque":["ArrayDeque","A fast resizable-array deque in Java. It is the usual choice for a stack or a queue instead of `Stack` or `LinkedList`."],"n_assignment":["Assignment","`age = 30` creates the name `age` and makes it refer to the value 30. Python variables are labels attached to objects, not boxes that hold values."],"n_autowired":["@Autowired","Asks Spring to inject a dependency. Prefer constructor injection; with a single constructor `@Autowired` is optional."],"n_aws":["AWS (Amazon Web Services)","Amazon's cloud platform: rentable servers (EC2), storage (S3), databases (RDS), networking (VPC) and hundreds of other services, billed by usage."],"n_b_ambiguity":["Handling ambiguity","Ask clarifying questions, state your assumptions, split the work into small steps, ship something early and iterate with feedback."],"n_b_career":["Career goals","Answer with growth in skills and responsibility (deeper technical expertise, leading small projects) that fits what the company offers. Be honest, not rehearsed."],"n_b_comm":["Communicating with non-technical people","Start from the goal and the impact, avoid jargon, use an analogy or example, and check understanding. Say what you need from them."],"n_b_conflict":["Conflict resolution","Listen first, find the shared goal, separate the problem from the person, bring data, agree on a next step. Show respect and a calm result, not who won."],"n_b_deadline":["Prioritization under pressure","Clarify what is urgent versus important, agree on scope with the stakeholders, deliver the most valuable part first, communicate risks early and say no to the rest."],"n_b_failure":["Learning from failure","Pick a real mistake, own it without blaming others, explain what you changed afterward (a test, a checklist, a process) and what you learned."],"n_b_feedback":["Receiving feedback","Listen without defending, ask questions to understand, thank the person, act on it and show the change. Interviewers look for a growth mindset."],"n_b_impact":["Impact and metrics","Close a story with a result and, if you can, a number: time saved, errors reduced, users helped. It turns 'I worked on it' into 'it mattered'."],"n_b_learning":["Learning quickly","Show a method: official docs, a small prototype, asking someone experienced, then applying it to real work. Give the result and how fast you got there."],"n_b_mentoring":["Mentoring","Helping someone grow: explain the why, give small tasks with feedback, pair on problems and let them own the solution. Describe how they improved."],"n_b_motivation":["Motivation for the role","Connect your goals to the role and the company: what you want to learn, what you can contribute and something specific you researched about their product or team."],"n_b_ownership":["Ownership","Showing that you took responsibility beyond your task: you saw the problem, acted, followed through and owned the result. Use 'I', not only 'we'."],"n_b_questions":["Questions for the interviewer","Ask about the team, how work is planned and reviewed, onboarding, what success looks like in 6 months and the main technical challenges. Avoid only asking about salary or perks."],"n_b_strengths":["Strengths and weaknesses","Strengths: pick 2 or 3 relevant ones with a short example. Weakness: a real one that is not critical for the job, plus what you do to improve it."],"n_b_teamwork":["Teamwork","Working well with others: share information, help teammates, give and accept review comments, respect different views and keep a positive attitude under pressure."],"n_b_tellme":["Present, past, future","A simple structure for 'Tell me about yourself': what you do now, how you got here (1 or 2 key steps), and why this role is next. About 1 to 2 minutes."],"n_bitwise":["Bitwise operators","`&` AND, `|` OR, `^` XOR, `<<` and `>>` shift bits. `n & (n - 1)` clears the lowest set bit, so it is 0 only for powers of two."],"n_box_sizing":["box-sizing: border-box","With `border-box`, `width` includes padding and border, so a 200px box stays 200px. With the default `content-box`, padding and border are added on top."],"n_builtin_exc":["Built-in exceptions","ValueError: right type, bad value. TypeError: wrong type. KeyError: missing dictionary key. IndexError: index out of range."],"n_cacheable":["@Cacheable","Caches the result of a method by its arguments. The next call with the same arguments returns the cached value without running the method."],"n_class_file":[".class file","A compiled Java file that contains bytecode. The JVM loads and runs it on any operating system."],"n_cls":["CLS (Cumulative Layout Shift)","A Core Web Vitals metric that measures how much the page layout jumps while it loads. Lower is better."],"n_command_pattern":["Command pattern","Wraps a request as an object, so it can be queued, logged, retried or undone. Natural fit for undo/redo and job queues."],"n_content_type":["Content-Type header","A header that says what format the body has, such as `application/json`."],"n_count":["COUNT(*) vs COUNT(column)","`COUNT(*)` counts all rows. `COUNT(column)` counts only rows where that column is NOT NULL."],"n_cpu":["CPU","Central Processing Unit: the chip that runs program instructions. 'CPU-bound' work is limited by how fast the chip can calculate."],"n_demeter":["Law of Demeter","'Talk only to your immediate friends.' A method should not reach through a chain of objects (`a.b.c.d()`); chains couple your code to the inner structure of other classes."],"n_dict_order":["Dict insertion order","Since Python 3.7 a dict keeps keys in the order they were inserted, and the language guarantees it (it was only a CPython detail in 3.6)."],"n_distinct":["DISTINCT","Removes duplicate rows from the result: `SELECT DISTINCT country FROM users` returns each country once."],"n_dry":["DRY","Don't Repeat Yourself: each piece of knowledge should live in one place, so a change needs only one edit."],"n_dynamic_array":["Dynamic array","An array that doubles its capacity when full (Python list, Java ArrayList). One append is occasionally O(n), but the amortized cost is O(1)."],"n_ebs":["EBS","Elastic Block Store: network disks for EC2 instances. The data stays when the instance stops, like a virtual hard drive."],"n_ecr_acr":["ECR / ACR","Managed container registries: Amazon Elastic Container Registry and Azure Container Registry. They store your Docker images privately."],"n_enter_exit":["__enter__ / __exit__","The two methods that make an object a context manager for `with`. `__enter__` runs at the start; `__exit__` always runs at the end, even after an error."],"n_entity":["@Entity","Marks a class as a JPA entity: Hibernate maps it to a database table and its fields to columns."],"n_entitygraph":["@EntityGraph / JOIN FETCH","Ways to load an entity together with its relations in a single query, which fixes the N+1 problem."],"n_eq_hash":["__eq__ / __hash__","`__eq__` defines `==`. If you define it, also define `__hash__` consistently (equal objects must have equal hashes) or the object misbehaves in sets and as dict keys."],"n_equality":["== vs === (JavaScript)","`==` converts types before comparing (`0 == \"\"` is true). `===` compares value AND type without converting (`0 === \"\"` is false). Prefer `===`."],"n_fetch":["fetch","The browser API for HTTP requests. It returns a Promise, does NOT throw on 404 or 500 (check `res.ok`), and `res.json()` is also async."],"n_fifo_lifo":["FIFO / LIFO","FIFO: first in, first out, like a queue at a shop. LIFO: last in, first out, like a stack of plates."],"n_floor_div":["/ vs // vs %","In Python 3, `/` always gives a float (`7 / 2` is `3.5`). `//` is floor division and rounds down (`7 // 2` is `3`). `%` gives the remainder (`7 % 2` is `1`)."],"n_floyd":["Floyd's cycle detection","Two pointers move through a linked list, one step and two steps at a time. If there is a cycle they meet; if not, the fast one reaches the end. Uses O(1) extra space."],"n_g1_zgc":["G1 / ZGC","Modern JVM garbage collectors. G1 is the default: it works in regions and aims at predictable pauses. ZGC aims at pauses of a few milliseconds even on huge heaps."],"n_gather":["asyncio.gather","Runs several coroutines concurrently and waits for all of them, returning their results in order."],"n_gcp":["GCP (Google Cloud Platform)","Google's cloud platform. It offers equivalents of the AWS and Azure services: Compute Engine (virtual machines), Cloud Storage (object storage) and GKE (managed Kubernetes)."],"n_git_cmds":["git add / commit / push / pull","`add` stages changes, `commit` saves a snapshot locally, `push` uploads commits to the remote, `pull` downloads and merges remote commits."],"n_hashset":["HashSet","A Java Set backed by a hash table: no duplicates, no order, average O(1) add and contains. It needs correct `equals` and `hashCode`."],"n_hpa":["HPA (Horizontal Pod Autoscaler)","A Kubernetes object that changes the number of Pod replicas based on CPU or custom metrics."],"n_init":["__init__","The initializer method that runs when a new object is created. It sets the starting attributes: `def __init__(self, name): self.name = name`."],"n_ip":["IP address","A number that identifies a device on a network, like 192.168.1.10 (IPv4). DNS translates names into IP addresses."],"n_iter_next":["__iter__ / __next__","The iterator protocol. `__iter__` returns the iterator; `__next__` returns the next item and raises `StopIteration` when there are no more."],"n_javac":["javac / java","`javac` compiles `.java` source into `.class` bytecode. `java` starts the JVM and runs that bytecode, or a whole JAR with `java -jar`."],"n_jdbctemplate":["JdbcTemplate","A Spring helper that runs SQL through JDBC and removes the boilerplate: connections, statements and cleanup are handled for you."],"n_jerrors":["StackOverflowError / OutOfMemoryError","StackOverflowError: the call stack is full, usually from infinite or very deep recursion. OutOfMemoryError: the heap has no room left even after garbage collection."],"n_jparepo":["JpaRepository","A Spring Data interface that gives ready-made CRUD, paging and sorting methods for an entity. You only declare the interface."],"n_json_loads":["json.loads / json.dumps","`json.loads` turns a JSON string into Python objects. `json.dumps` turns Python objects into a JSON string."],"n_jsx":["JSX","A syntax that lets you write HTML-like markup inside JavaScript (React). The build step compiles it into normal function calls."],"n_latest_tag":["latest tag","Docker's default tag. It is only a name that moves, so it does not mean 'newest'. Pin an exact version in production."],"n_lock_order":["Lock ordering","The standard way to avoid deadlocks: every transaction takes locks in the same global order, and keeps transactions short."],"n_longadder":["LongAdder","A Java counter built for many threads: it spreads updates over several cells and sums them on read, so it scales better than `AtomicLong` under contention."],"n_lru_cache":["functools.lru_cache","A decorator that remembers the results of a function for the same arguments (memoization). Arguments must be hashable, so passing a list raises `TypeError`."],"n_maven_layout":["Maven folder layout","The standard layout: `src/main/java` (code), `src/main/resources` (config), `src/test/java` (tests). Build output goes to `target/`."],"n_multiprocessing":["multiprocessing","Runs Python code in separate processes, each with its own interpreter and GIL, so CPU-bound work uses several cores. Cost: starting processes and pickling the data sent between them."],"n_mvn_cmds":["mvn clean / test / package / install","`clean` deletes `target/`, `test` runs the unit tests, `package` builds the JAR, `install` also copies it into `~/.m2`."],"n_nist":["NIST","The US National Institute of Standards and Technology. It publishes widely used security and cloud standards, such as the definition of cloud computing."],"n_null_compare":["Comparing with NULL","NULL means 'unknown', so `= NULL` is never true. Use `IS NULL` and `IS NOT NULL`."],"n_oidc":["OIDC (OpenID Connect)","A login layer on top of OAuth 2.0. It tells the app who the user is through an ID token (a JWT)."],"n_os":["Operating system (OS)","The software that manages the hardware and runs other programs (Linux, Windows, macOS). It gives programs files, memory, processes and networking."],"n_override":["@Override","Tells the compiler that this method must override one from a parent class or interface. If the signature does not match, compilation fails."],"n_permutations":["Permutations (n!)","The number of ways to order n distinct items is n! (n factorial). Generating them all takes at least n! steps, which grows extremely fast."],"n_pid":["PID","Process ID: the number the operating system gives to each running process. In a container, PID 1 is the main process; when it exits, the container stops."],"n_plus_1":["N+1 query problem","Running 1 query to get a list of N items, then 1 more query for each item. Fixed by loading related data in bulk (JOIN or IN query)."],"n_print_return":["print vs return","`print` shows a value on the screen and the function then returns `None`. `return` hands a value back to the caller so other code can use it, and it ends the function."],"n_promise_all":["Promise.all","Runs promises in parallel and resolves with all results, but rejects as soon as ONE rejects. `Promise.allSettled` waits for all and reports each outcome."],"n_pyproject":["pyproject.toml","The standard config file of a Python project: metadata, dependencies and tool settings in one place."],"n_quic":["QUIC","A modern transport protocol built on UDP and used by HTTP/3. It sets up connections faster and avoids TCP head-of-line blocking."],"n_ram":["RAM","Random-access memory: fast, temporary memory where running programs keep their data. It is cleared when the program ends or the computer restarts."],"n_rbac":["RBAC","Role-Based Access Control: permissions are given to roles (admin, editor, viewer) and users receive roles, instead of assigning permissions one by one."],"n_resttemplate":["RestTemplate","Spring's classic HTTP client for calling other REST services. In newer code `RestClient` or `WebClient` is preferred."],"n_retry_after":["Retry-After header","A header sent with 429 or 503 that tells the client how many seconds to wait before trying again."],"n_sdk":["SDK","Software Development Kit: a library plus tools that a vendor provides to use its service from code, for example the AWS SDK."],"n_seo":["SEO","Search Engine Optimization: making pages easy for search engines to read and rank. Server-rendered HTML helps because crawlers see the content immediately."],"n_sha":["SHA-256 / SHA","The Secure Hash Algorithm family. SHA-256 turns any input into a fixed 256-bit fingerprint. It is fast and one-way, so for passwords use slow hashes (Argon2, bcrypt) instead."],"n_sleep":["time.sleep vs asyncio.sleep","`time.sleep` blocks the whole thread. Inside async code use `await asyncio.sleep(...)`, which lets other tasks run while waiting."],"n_slicing":["Slicing and negative indexes","`seq[start:stop:step]` takes a part of a list, tuple or string. `start` is included, `stop` is NOT. Negative indexes count from the end: `s[-1]` is the last item, so `\"python\"[-1]` is `'n'`."],"n_sql_clauses":["SELECT / WHERE / HAVING / ORDER BY","SQL clauses are evaluated in this logical order: FROM, WHERE (filters rows), GROUP BY, HAVING (filters groups), SELECT (picks columns), ORDER BY, LIMIT."],"n_star":["STAR method","Situation, Task, Action, Result: a structure for answering behavioral questions with a short, concrete story."],"n_tcp":["TCP","Transmission Control Protocol: a reliable connection between two machines. It guarantees that data arrives complete and in order. HTTP, databases and SSH run on top of it."],"n_testid":["data-testid","An HTML attribute added only for tests, so that a selector stays stable when the styles or the text change."],"n_to_thread":["asyncio.to_thread","Runs a blocking function in a worker thread so that it does not freeze the event loop."],"n_token_bucket":["Token bucket","A rate limiting algorithm: tokens refill at a steady rate and each request spends one. It allows short bursts (up to the bucket size) while keeping the average rate under control."],"n_typevar":["TypeVar","A placeholder type used for generic code. `T = TypeVar(\"T\")` lets a function say 'the output has the same type as the input'."],"n_udp":["UDP","A faster, connectionless protocol with no delivery guarantee. Used for video calls, games, DNS lookups and HTTP/3 (through QUIC)."],"n_useeffect":["useEffect","A React hook for side effects (fetching, subscriptions, timers) that run after render. The dependency array controls when it re-runs; the returned function cleans up."],"n_useref":["useRef","A React hook that keeps a mutable value or a DOM node between renders without causing a re-render."],"n_usestate":["useState","A React hook that gives a component a piece of state: `const [count, setCount] = useState(0)`. Calling the setter schedules a re-render."],"n_uuid":["UUID","Universally Unique Identifier: a 128-bit random ID like `3f2b8c1e-...`. It can be generated anywhere without coordination, with a negligible chance of collision."],"n_vpn":["VPN","Virtual Private Network: an encrypted tunnel between networks or devices over the internet, so they behave as if they were on the same private network."],"n_waf":["WAF","Web Application Firewall: filters HTTP traffic and blocks common attacks like SQL injection and XSS before they reach the app."],"n_war":["WAR file","Web Application Archive: a packaged Java web app that is deployed into a servlet container such as Tomcat. Spring Boot usually builds an executable JAR instead."],"n_wip":["WIP limit","Work-in-progress limit: a Kanban rule that caps how many items can sit in a column at once, so the team finishes work before it starts more."],"n_wraps":["functools.wraps","A decorator for decorators: it copies the original function's name and docstring onto the wrapper, so debugging and introspection still work."],"n_yagni":["YAGNI","You Aren't Gonna Need It: do not build a feature until it is really needed."],"n_yield":["yield","Turns a function into a generator: it pauses and hands back a value, then resumes where it stopped on the next call."],"normalization":["Normalization","Organizing tables so each fact is stored once, linked by keys. Avoids duplicate data and update mistakes."],"nosql":["NoSQL","Databases that are not relational tables: document, key-value, wide-column or graph stores, often with flexible schemas."],"null":["NULL","A marker for 'missing or unknown value' in SQL. It is not 0 or empty string, and comparisons with it are never true (use IS NULL)."],"o_azure_map":["AWS to Azure mapping","EC2 = VM; S3 = Blob Storage; Lambda = Functions; EKS = AKS; RDS = Azure SQL; DynamoDB = Cosmos DB; IAM = Entra ID + RBAC; CloudWatch = Azure Monitor."],"o_azure_rg":["Azure resource group","A logical container for resources that share a lifecycle. Subscriptions hold resource groups; resource groups hold resources."],"o_cicd_tools":["CI/CD tools","Jenkins, GitHub Actions, GitLab CI and Azure DevOps Pipelines run build, test and deploy steps defined as code."],"o_cidr":["CIDR notation","Writing a network range as address/prefix, e.g. `10.0.1.0/24` = 256 addresses. A smaller prefix number means a bigger network."],"o_configmap":["ConfigMap","A Kubernetes object holding non-sensitive configuration injected into Pods as environment variables or files."],"o_crashloop":["CrashLoopBackOff","A Pod state meaning the container keeps crashing and Kubernetes retries with increasing delays."],"o_dns_records":["DNS records","A: name to IPv4. AAAA: name to IPv6. CNAME: alias to another name. MX: mail servers. TXT: free text such as verification."],"o_docker_cli":["Docker CLI","Command-line tool: `docker build` (make an image), `run` (start a container), `ps` (list), `logs`, `exec` (shell inside), `stop`, `rm`."],"o_ec2":["Amazon EC2","AWS virtual servers (virtual machines) that you configure and manage."],"o_ecs_eks":["ECS / EKS / Fargate","ECS: AWS's container orchestrator. EKS: managed Kubernetes. Fargate: serverless compute for containers, so you manage no nodes."],"o_helm":["Helm","The Kubernetes package manager: charts of templated manifests installed with per-environment values."],"o_hybrid":["Hybrid connectivity","Connecting on-premises networks to the cloud with a site-to-site VPN or a dedicated line (Direct Connect, ExpressRoute)."],"o_iaas":["IaaS / PaaS / SaaS","Infrastructure, Platform and Software as a Service: rented servers; a platform that runs your code; a finished application."],"o_ingress":["Ingress","Kubernetes rules that route external HTTP(S) traffic by host and path to Services, implemented by an Ingress Controller."],"o_kubectl":["kubectl","The Kubernetes command-line tool: `apply`, `get`, `describe`, `logs`, `exec`, `rollout`."],"o_l4_l7":["Layer 4 vs layer 7","Layer 4 balances raw TCP/UDP connections; layer 7 understands HTTP and can route by URL path or host name."],"o_managed_identity":["Managed identity","An identity Azure manages for a resource so it can call other services with tokens instead of stored passwords. AWS equivalent: IAM roles."],"o_namespace":["Namespace (Kubernetes)","A logical partition of a cluster (dev, staging, team-a) with its own names, quotas and permissions."],"o_nat":["NAT","Network Address Translation: lets hosts with private IPs reach the internet through a shared public address."],"o_private_link":["Private endpoint / PrivateLink","Gives a cloud service a private IP in your network, so traffic never crosses the public internet."],"o_pvc":["PersistentVolume / Claim","PV: a piece of cluster storage. PVC: a Pod's request for storage; it binds to a PV so data survives Pod restarts."],"o_rds_dynamo":["RDS / DynamoDB","RDS: managed relational databases. DynamoDB: serverless NoSQL key-value/document store for massive scale and simple access patterns."],"o_registry":["Container registry","A service storing container images for push/pull: Docker Hub, AWS ECR, Azure ACR."],"o_resources":["Requests and limits","Kubernetes CPU/memory settings: requests are reserved for scheduling; limits are the maximum (memory over the limit means OOMKilled)."],"o_security_group":["Security Group / NSG","A virtual firewall attached to a resource: stateful and allow-only (AWS Security Group, Azure NSG). NACLs are stateless subnet-level filters."],"o_shared_resp":["Shared responsibility model","The provider secures the cloud infrastructure; the customer secures their data, identities, configuration and code."],"o_statefulset":["StatefulSet / DaemonSet / Job","StatefulSet: Pods with stable identity and storage (databases). DaemonSet: one Pod per node. Job: a run-to-completion task; CronJob: scheduled Jobs."],"o_vpc":["VPC / VNet","A private, isolated virtual network in AWS (VPC) or Azure (VNet), divided into subnets."],"o_yaml":["YAML","A human-readable configuration format based on indentation, used by Kubernetes, Docker Compose, Spring and many CI tools."],"oauth":["OAuth 2.0","A standard for letting an app get limited access to a user's account on another service without seeing the user's password ('Log in with Google')."],"object":["Object","Any value in Python (a number, a list, a function, a class). Every object has a type, a value and an identity."],"object_storage":["Object storage","Storage for files (objects) accessed via an HTTP API, like S3. Very durable and scalable, but not a normal filesystem."],"observability":["Observability","How well you can understand what a running system is doing from its outputs: metrics, logs and traces."],"observer":["Observer pattern","Subscribers register with a subject and are notified automatically when an event happens (publish/subscribe)."],"ocp":["Open/Closed Principle","Code should be open for extension (add new behavior) but closed for modification (don't edit tested code to add it)."],"oom":["OOM killer","Out Of Memory killer: a Linux kernel mechanism that kills a process using more memory than allowed."],"optimistic_locking":["Optimistic locking","Not locking while reading; when saving, check a version number to detect if someone else changed the row in the meantime."],"origin":["Origin","The combination of scheme, domain and port of a web page, e.g. https://app.example.com:443. Different origin = different site for the browser."],"orm":["ORM","Object-Relational Mapper (Django ORM, SQLAlchemy): lets you work with database rows as Python objects instead of writing SQL by hand."],"owasp":["OWASP Top 10","A widely used list, published by the OWASP foundation, of the most critical security risks for web applications."],"pagination":["Pagination","Returning a large list in smaller pages (e.g. 20 items at a time), using limit/offset or a cursor."],"parametrize":["parametrize","A pytest decorator that runs the same test with several sets of inputs."],"partition":["Network partition","A failure where parts of a distributed system cannot communicate with each other, while each part keeps running."],"password_hashing":["Password hashing","Storing a slow, salted, one-way hash of the password (Argon2id, bcrypt, scrypt) instead of the password itself."],"path_param":["Path parameter","A variable part of the URL path that identifies a resource: in `/users/42`, 42 is the user ID."],"path_traversal":["Path traversal","Using `../` sequences in a file path input to access files outside the intended folder."],"pessimistic_locking":["Pessimistic locking","Locking rows when you read them (SELECT ... FOR UPDATE) so nobody else can change them until you finish."],"phishing":["Phishing","Fraudulent messages that impersonate trusted organizations to trick people into giving credentials or installing malware."],"pickle":["Pickle","Python's built-in way to convert objects to bytes and back. Used to send data between processes. Never unpickle untrusted data."],"pipeline":["CI/CD pipeline","An automated sequence of steps (lint, test, build, deploy) triggered by code changes."],"pod":["Pod","The smallest unit Kubernetes runs: one or more containers sharing network and storage."],"polling":["Polling","The client repeatedly asks the server 'anything new?' at intervals. Simple but wasteful compared to push."],"polymorphism":["Polymorphism","Different classes respond to the same method call in their own way. The caller just calls `x.area()` without checking the type."],"port":["Port","A number (0-65535) that identifies a specific service on a machine, e.g. 443 for HTTPS, 5432 for PostgreSQL."],"positional_arg":["Positional argument","An argument passed by position: `f(10, 20)`. The first value goes to the first parameter, and so on."],"postmortem":["Postmortem","A written analysis after an incident: what happened, why, and what will change to prevent it."],"prefix_sum":["Prefix sum","An array where each position holds the total of all elements before it, so any range sum is one subtraction."],"primary_key":["Primary key","The column(s) that uniquely identify each row in a table. Unique and never NULL."],"probe":["Readiness / liveness probe","Health checks Kubernetes runs on Pods: readiness decides if a Pod gets traffic; liveness decides if it must be restarted."],"process":["Process","A running program with its own private memory. Two processes do not share variables; to exchange data they must send it to each other. Like two separate kitchens."],"promise":["Promise","An object representing the future result of an async operation: pending, then fulfilled with a value or rejected with an error."],"property":["@property","Turns a method into an attribute you read without parentheses: `circle.area`. Lets you compute or validate values while keeping simple syntax."],"property_based":["Property-based testing","Testing that a rule holds for many automatically generated inputs (e.g. with Hypothesis)."],"props":["Props","Inputs passed from a parent component to a child component. Read-only for the child."],"protocol":["Protocol (typing)","A type describing required methods. Any class that has those methods matches it, without inheriting from it."],"pub_sub":["Pub/sub","Publish/subscribe messaging: publishers send to a topic; every subscriber of that topic receives a copy."],"pytest":["pytest","The most popular Python testing framework: plain `assert` statements, fixtures, parametrization and plugins."],"qps":["QPS","Queries (requests) per second: a basic measure of load used in capacity estimates."],"query_param":["Query parameter","Key=value pairs after `?` in a URL, used for filtering, sorting and paging: `?status=paid&limit=10`."],"queue":["Queue","A FIFO collection (first in, first out): add at the back, remove from the front. Like a line of people."],"quicksort":["Quicksort","A sort that picks a pivot, splits items into smaller and bigger than the pivot, and sorts each part. Fast on average, O(n²) worst case."],"race_condition":["Race condition","A bug where the result depends on the unlucky timing of threads or processes touching the same data. Hard to reproduce because it happens only sometimes."],"rate_limit":["Rate limiting","Restricting how many requests a client may make per time window, to protect the service from abuse and overload."],"rce":["RCE (Remote Code Execution)","A vulnerability that lets an attacker run their own code on your server. The most severe class of bug."],"react":["React","A JavaScript library for building user interfaces from components that re-render when their data changes."],"read_replica":["Read replica","A copy of the database that receives changes from the primary and serves read queries."],"rebase":["Rebase","Replaying your commits on top of another branch to get a straight-line history. It rewrites commit IDs."],"reconciliation":["Reconciliation","React's process of comparing the new UI description with the previous one and updating only what changed."],"recursion":["Recursion","A function that solves a problem by calling itself on smaller inputs, until it reaches a base case."],"redis":["Redis","A very fast in-memory key-value data store, used for caching, counters, sessions, queues and leaderboards."],"refactoring":["Refactoring","Improving the internal structure of code (names, duplication, organization) without changing its behavior."],"reference_counting":["Reference counting","CPython counts how many variables or containers point to each object. When the count drops to 0, the object is freed immediately."],"regression":["Regression","A bug where something that used to work stops working after a change. Regression tests guard against it."],"replication":["Replication","Keeping copies of the same data on several servers, for availability and to spread read traffic."],"repository":["Repository","A class that hides how data is stored, offering simple methods like `get`, `add`, `list` to the rest of the code."],"repr":["__repr__ vs __str__","`__repr__` gives an exact, developer-oriented description of an object; `__str__` gives friendly text for users. print() uses __str__; lists and the debugger use __repr__."],"responsive":["Responsive design","Designing pages that adapt their layout to different screen sizes, from phones to desktops."],"rest":["REST","A popular style for web APIs: URLs name resources (`/users/42`), HTTP methods express actions, and requests are stateless."],"retry_backoff":["Retry with exponential backoff","Retrying a failed call after waiting longer each time (1 s, 2 s, 4 s...), with some randomness (jitter) so clients don't retry in sync."],"reverse_proxy":["Reverse proxy","A server in front of your app servers that receives client requests and forwards them, often adding TLS, caching and load balancing."],"rollback":["Rollback","Returning to the previous working version after a bad release."],"routing":["Routing","Mapping incoming request paths and methods to the functions that handle them."],"s3":["Amazon S3","AWS object storage service for files of any size, organized in buckets."],"s_defense_depth":["Defense in depth","Layering several independent security controls so one failure does not break the whole defense."],"s_kms":["KMS / Key Vault","Managed services that create, store and control encryption keys (AWS KMS, Azure Key Vault)."],"s_sast_dast":["SAST / DAST / SCA","SAST scans source code statically; DAST attacks a running app; SCA checks third-party dependencies for known vulnerabilities."],"s_sbom":["SBOM","Software Bill of Materials: a list of every component and dependency inside your software, used to find vulnerable libraries quickly."],"s_threat_model":["Threat modeling / STRIDE","A design-time analysis of what can go wrong. STRIDE = Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege."],"salt":["Salt","A random value added to each password before hashing so that identical passwords produce different hashes."],"schema":["Schema","The structure of the data: which tables or documents exist, their fields, types and relationships."],"scope":["Scope","Where a variable name is visible. Python looks names up in this order: Local (inside the function), Enclosing function, Global (module), Built-in (LEGB)."],"secret":["Secret","Sensitive configuration such as passwords, API keys and private keys. Must never be stored in code or logs."],"selector":["CSS selector","A pattern that chooses which elements a rule applies to: `p` (elements), `.card` (class), `#main` (id), `a:hover` (state)."],"semantic_html":["Semantic HTML","Using HTML elements for their meaning (button, nav, main, label) instead of generic divs, which helps accessibility and SEO."],"semver":["Semantic Versioning","Version numbers MAJOR.MINOR.PATCH: breaking change, new compatible feature, compatible bug fix."],"serverless":["Serverless","Running code without managing servers: the provider runs your function on demand and charges per execution (e.g. AWS Lambda)."],"service_k8s":["Service (Kubernetes)","A stable network name and IP that load-balances traffic to a changing set of Pods."],"session":["Session","Server-side memory of a logged-in user, identified by a random session ID usually stored in a cookie."],"session_fixation":["Session fixation","An attack where the victim is made to log in with a session ID the attacker already knows."],"set":["Set","An unordered collection of unique values with very fast membership checks: `{1, 2, 3}`."],"shallow_copy":["Shallow copy","A new container that holds the SAME inner objects as the original: `list(a)`, `a.copy()`, `copy.copy(a)`."],"sharding":["Sharding","Splitting data across several servers by a key (e.g. user ID), so each holds only part of the data."],"signal":["Signal (Unix)","A message sent to a process: SIGTERM (15) politely asks it to stop; SIGKILL (9) kills it immediately."],"singleton":["Singleton","A class that allows only one instance, reachable from anywhere. Often criticized because it acts like a global variable."],"sli_slo_sla":["SLI / SLO / SLA","SLI: a measured indicator (e.g. success rate). SLO: the internal target (e.g. 99.9%). SLA: a contractual promise to customers."],"sliding_window":["Sliding window","A technique that keeps a moving range [left, right] over an array or string, expanding and shrinking it instead of restarting, often O(n)."],"slots":["__slots__","A class setting that lists the only attribute names its objects may have. It removes the per-object dictionary to save memory."],"smoke_test":["Smoke test","A small set of quick checks that the most important functions work, typically after a deploy."],"solid":["SOLID","Five design principles for maintainable object-oriented code: Single responsibility, Open/closed, Liskov substitution, Interface segregation, Dependency inversion."],"sorting":["Sorting algorithm","A method to put items in order. Common ones: merge sort, quicksort, heapsort, Timsort (Python). Good general sorts are O(n log n)."],"sp_actuator":["Spring Boot Actuator","Adds operational endpoints (health, metrics, info) for monitoring and orchestrator probes."],"sp_aop":["AOP (Aspect-Oriented Programming)","A technique to apply cross-cutting behavior (logging, security, transactions) around many methods without editing them."],"sp_autoconfig":["Auto-configuration","Spring Boot's mechanism to register beans automatically based on the libraries on the classpath and your properties; it backs off when you define your own."],"sp_bean":["Bean","An object created and managed by the Spring container. You get beans by annotating classes (`@Component`, `@Service`) or declaring `@Bean` methods."],"sp_bean_scope":["Bean scope","How many instances of a bean exist. Default `singleton` (one per container); also `prototype`, `request`, `session`."],"sp_bean_validation":["Bean Validation","Declarative rules on fields (`@NotBlank`, `@Email`, `@Size`) checked when you add `@Valid` to a parameter."],"sp_component_scan":["Component scan","Spring searching a package and its sub-packages for stereotype-annotated classes to register as beans."],"sp_config_props":["@ConfigurationProperties","Binds groups of properties from `application.yml` to a typed Java class, instead of reading single values with `@Value`."],"sp_configuration":["@Configuration","A class that declares beans with `@Bean` methods."],"sp_constructor_injection":["Constructor injection","Providing dependencies as constructor parameters. Allows `final` fields, clear requirements and easy unit testing."],"sp_controller_advice":["@ControllerAdvice","A class that applies exception handling (and other advice) to all controllers in one place."],"sp_data_jpa":["Spring Data JPA","A Spring module that generates repository implementations from interfaces, including queries derived from method names."],"sp_dispatcher":["DispatcherServlet","Spring MVC's front controller: the single entry point that routes each HTTP request to the right controller method."],"sp_dto":["DTO (Data Transfer Object)","A simple class (often a record) shaped for an API request or response, separate from the database entity."],"sp_hibernate":["Hibernate","The most popular JPA implementation. It generates SQL, manages entity state and caches loaded objects."],"sp_ioc":["Inversion of Control (IoC)","A design where a framework or container controls object creation and wiring instead of your own code calling `new`."],"sp_jackson":["Jackson","The default Java library that converts objects to JSON and JSON to objects."],"sp_jakarta":["Jakarta EE","The successor to Java EE. Since Spring Boot 3 the packages are `jakarta.*` instead of `javax.*`."],"sp_jdbc":["JDBC","The standard low-level Java API for running SQL on relational databases through drivers."],"sp_jpa":["JPA (Jakarta Persistence)","The Java standard for mapping objects to relational tables (ORM): `@Entity`, `@Id`, relationships and JPQL queries."],"sp_lazy_loading":["Lazy loading","Loading related data only when it is first accessed. Efficient, but outside a session it throws LazyInitializationException."],"sp_path_variable":["@PathVariable","Binds a part of the URL path to a method parameter: `/users/{id}`."],"sp_persistence_context":["Persistence context","The set of entities a JPA session currently manages. Changes to them are detected (dirty checking) and written at commit."],"sp_profile":["Spring profile","A named configuration set (dev, test, prod) activated with `spring.profiles.active`, letting the same app use different settings per environment."],"sp_proxy":["Spring proxy","A wrapper object Spring places around a bean to add behavior (transactions, caching, security). Calls inside the same class bypass it."],"sp_request_body":["@RequestBody","Binds the HTTP request body (JSON) to a Java method parameter."],"sp_rest_controller":["@RestController","A controller whose methods return data written straight to the HTTP response body (usually JSON), rather than a view name."],"sp_security":["Spring Security","The Spring module for authentication, authorization and protection against common attacks (CSRF, session fixation...), built on a chain of servlet filters."],"sp_servlet":["Servlet / servlet container","A servlet is a Java class that handles HTTP requests; a container (Tomcat, Jetty) runs them and manages connections and threads."],"sp_spring":["Spring Framework","A large Java framework for building applications. Its core is a container that creates objects (beans) and wires them together, with modules for web, data, security and testing."],"sp_spring_boot":["Spring Boot","A layer on top of Spring that auto-configures libraries, bundles dependencies into starters and embeds a web server, so apps start with `java -jar`."],"sp_starter":["Starter","A single Maven/Gradle dependency (like `spring-boot-starter-web`) that pulls in a compatible group of libraries for one purpose."],"sp_stereotype":["Stereotype annotations","`@Component`, `@Service`, `@Repository`, `@Controller` and `@RestController`: markers that register a class as a bean and describe its role."],"sp_test_slice":["Test slice","A Spring Boot test annotation that loads only part of the app (`@WebMvcTest`, `@DataJpaTest`) for fast, focused tests."],"sp_transactional":["@Transactional","Runs a method inside a database transaction: commit on success, roll back on a RuntimeException by default."],"space_complexity":["Space complexity","How much extra memory an algorithm needs as the input grows, written in Big-O."],"specificity":["Specificity","The weight CSS uses to choose between conflicting rules: inline > id > class > element."],"spof":["Single point of failure","A component without a backup whose failure stops the whole system."],"sql":["SQL","Structured Query Language: the language used to read and change data in relational databases (SELECT, INSERT, UPDATE, DELETE)."],"sql_injection":["SQL injection","An attack where user input is inserted into a SQL query as code, letting the attacker read or change data. Prevented with parameterized queries."],"sqs_sns":["SQS / SNS","AWS messaging: SQS is a queue that workers pull from; SNS publishes each message to all subscribers."],"srp":["Single Responsibility Principle","A class or module should have one job, so only one kind of change forces you to edit it."],"ssh":["SSH","Secure Shell: an encrypted protocol to log in to and run commands on remote machines."],"ssr":["SSR","Server-side rendering: the server generates the HTML for a page so it arrives already filled with content."],"ssrf":["SSRF","Server-Side Request Forgery: making your server send requests to internal or unintended addresses."],"stack":["Stack","A LIFO collection (last in, first out): push adds to the top, pop removes from the top. Like a pile of plates."],"staging":["Staging environment","A production-like environment used to test releases before they reach real users."],"state":["State (UI)","Data owned by a component that can change over time; changing it causes a re-render."],"stateless":["Stateless","The server keeps no memory of previous requests from a client; each request carries all it needs (e.g. a token)."],"status_code":["Status code","A 3-digit number in every HTTP response: 2xx success, 3xx redirect, 4xx client error, 5xx server error."],"strategy":["Strategy pattern","Interchangeable algorithms behind one interface, chosen at runtime (e.g. different shipping cost rules)."],"structural_typing":["Structural typing","Type compatibility based on the shape (properties and methods) of a value, not the name of its type."],"stub":["Stub","A test double that returns fixed, pre-programmed answers."],"symmetric":["Symmetric encryption","Encryption where the same secret key encrypts and decrypts (e.g. AES). Fast."],"t_explicit_wait":["Explicit wait","Waiting until a specific condition is true (element visible, clickable) with a timeout, instead of sleeping a fixed time."],"t_junit":["JUnit 5","The standard Java unit testing framework: `@Test`, `@BeforeEach`, `@ParameterizedTest`, assertions and extensions."],"t_locator":["Locator","The way a test finds an element: by id, name, CSS selector, XPath or link text. Stable locators make tests less brittle."],"t_pom":["Page Object Model","A pattern where each page is a class with its locators and actions, keeping tests readable and UI changes in one place."],"t_selenium":["Selenium WebDriver","A library that controls a real browser from code (open pages, find elements, click, type) to automate UI tests."],"table":["Table","A set of rows (records) with the same columns (fields), like a spreadsheet with strict column types."],"tdd":["TDD (Test-Driven Development)","Writing a failing test first, then just enough code to pass it, then cleaning up: red → green → refactor."],"terraform":["Terraform","A popular Infrastructure-as-Code tool that creates and updates cloud resources from configuration files."],"test_isolation":["Test isolation","Each test sets up and cleans up its own data, so tests don't affect each other and can run in any order."],"test_pyramid":["Test pyramid","Guideline for test mix: many fast unit tests at the bottom, fewer integration tests, very few slow end-to-end tests at the top."],"this_js":["this (JavaScript)","A keyword whose value depends on how a function is called. Arrow functions take `this` from the surrounding code."],"thread":["Thread","A sequence of instructions running inside a program. One program (process) can have several threads that share the same memory, like several cooks in one kitchen."],"throttle":["Throttle","Limiting a function to run at most once per time interval, even if events keep firing (e.g. scrolling)."],"throughput":["Throughput","How much work a system completes per unit of time, e.g. requests per second."],"time_complexity":["Time complexity","How the number of steps of an algorithm grows with the input size, usually written in Big-O."],"tls":["TLS","Transport Layer Security: the protocol that encrypts and authenticates network connections. The S in HTTPS."],"token":["Token","A string a client sends to prove who it is (like a ticket), usually in the `Authorization` header. It replaces sending the password every time."],"topological_sort":["Topological sort","Ordering the nodes of a DAG so that every node comes after the nodes it depends on."],"transaction":["Transaction","A group of database operations treated as one unit: either all succeed (COMMIT) or all are undone (ROLLBACK)."],"tree":["Tree","A hierarchical structure of nodes: one root, each node has children, no cycles. Nodes without children are leaves."],"trie":["Trie (prefix tree)","A tree where each path from the root spells a prefix; used for autocomplete and prefix searches."],"try_except":["try / except","Syntax to catch errors: code that might fail goes in `try`; the handling code goes in `except SomeError:`. `finally` always runs; `else` runs only if there was no error."],"ttl":["TTL (time to live)","How long a cached item (or DNS record) stays valid before it expires and must be fetched again."],"twelve_factor":["Twelve-Factor App","A set of 12 practices for cloud-friendly apps, such as config in env vars, stateless processes and logs to stdout."],"two_pointers":["Two pointers","A technique using two indexes that move through the data (from both ends, or one fast and one slow) to avoid nested loops."],"type_hint":["Type hints","Annotations like `def f(x: int) -> str:` that document expected types. Python ignores them at runtime; tools like mypy and editors use them to find bugs."],"typescript":["TypeScript","JavaScript with static type annotations, checked at compile time and removed when compiled to JS."],"union":["UNION","Combines the results of two SELECT queries into one list. UNION removes duplicates; UNION ALL keeps them."],"union_find":["Union-Find (disjoint set)","A structure that tracks which elements belong to the same group, with near-O(1) find and union operations."],"unique_constraint":["UNIQUE constraint","A rule that no two rows may have the same value in that column (e.g. email)."],"unit_test":["Unit test","An automated test of a small piece of code (a function or class) in isolation, with external dependencies replaced by test doubles."],"v_bom":["BOM / parent POM","A pom that fixes the versions of many libraries so they are compatible and you do not repeat version numbers."],"v_branching_strategy":["Branching strategy","A team's rules for branches: Git Flow (develop/release/hotfix) or trunk-based (frequent merges to main)."],"v_cherry_pick":["git cherry-pick","Copies the changes of one specific commit onto the current branch as a new commit."],"v_dep_scope":["Dependency scope","Tells Maven when a dependency is needed: compile (default), provided, runtime or test."],"v_gav":["GAV coordinates","groupId, artifactId and version: the three values that uniquely identify a Maven artifact."],"v_git":["Git","A distributed version control system that records the history of your files and supports branches and merging."],"v_gitignore":["`.gitignore`","A file listing patterns of files Git should not track, such as build output, IDE settings and secrets."],"v_local_repo":["Local Maven repository","The folder `~/.m2/repository` where Maven caches downloaded libraries and stores artifacts from `mvn install`."],"v_maven":["Maven","A Java build and dependency management tool. It reads `pom.xml`, downloads libraries, compiles, tests and packages the project."],"v_maven_lifecycle":["Maven lifecycle","The ordered phases of a build: validate, compile, test, package, verify, install, deploy. Running a phase runs all earlier ones."],"v_merge_conflict":["Merge conflict","Happens when two branches changed the same lines. You must pick the final content manually, then mark it resolved."],"v_pom":["pom.xml","Project Object Model: the Maven file describing the project (coordinates, dependencies, plugins, properties)."],"v_pull_request":["Pull request","A request to merge a branch, with code review and automated checks, hosted on GitHub/GitLab (called merge request on GitLab)."],"v_reflog":["git reflog","A local log of everywhere HEAD has pointed, used to recover \"lost\" commits after a reset or rebase."],"v_remote":["Remote repository","A shared copy of the Git repository hosted elsewhere (GitHub, GitLab). `origin` is the default name of the main remote."],"v_reset_revert":["git reset vs git revert","`reset` moves a branch back and rewrites history; `revert` adds a new commit that undoes an earlier one, safe on shared branches."],"v_sdlc":["SDLC","Software Development Life Cycle: the phases from requirements and design through coding, testing, deployment and maintenance."],"v_snapshot":["SNAPSHOT version","A mutable development version (`1.2.0-SNAPSHOT`) that may change, unlike an immutable release version."],"v_staging":["Staging area (index)","The waiting area where `git add` places changes you want in the next commit."],"v_stash":["git stash","Temporarily stores uncommitted changes so you can switch tasks and bring them back later."],"v_transitive":["Transitive dependency","A library pulled in automatically because one of your dependencies needs it."],"validation":["Validation","Checking that input data has the right shape, types and values before using it. In FastAPI done by Pydantic models."],"var_let_const":["var / let / const","Ways to declare variables in JS. var: function-scoped and hoisted (old). let: block-scoped, can be reassigned. const: block-scoped, cannot be reassigned."],"venv":["Virtual environment","A self-contained folder with its own Python packages for one project, created with `python -m venv .venv`."],"versioning":["API versioning","Labeling API versions (e.g. /v1, /v2) so you can introduce breaking changes without breaking existing clients."],"vertical_scaling":["Vertical scaling","Making one server more powerful (more CPU, RAM, disk). Simple but limited and still a single point of failure."],"virtual_dom":["Virtual DOM","A lightweight in-memory description of the UI that React compares between renders to compute minimal real DOM changes."],"vm":["Virtual machine","A software emulation of a full computer, running its own operating system on top of a hypervisor."],"volume":["Volume","Storage that lives outside a container's lifecycle, used to keep data such as database files."],"web_storage":["localStorage / sessionStorage","Browser key-value storage readable by JavaScript. localStorage persists; sessionStorage lasts for one tab."],"webhook":["Webhook","An HTTP call that a service makes to YOUR URL when an event happens (e.g. 'payment succeeded'), instead of you asking repeatedly."],"websocket":["WebSocket","A connection that stays open so server and client can send messages to each other at any time. Used for chat and live updates."],"window_function":["Window function","A function computed over a set of related rows while keeping every row: ROW_NUMBER, RANK, running totals, using OVER (PARTITION BY ... ORDER BY ...)."],"worker":["Worker","A process or thread that handles requests or jobs. A server often runs several workers to handle work in parallel."],"write_through":["Write-through cache","Every write goes to both the cache and the database, so the cache is always current."],"wsgi_asgi":["WSGI / ASGI","Standards for how Python web servers run web apps. WSGI is synchronous (Flask, classic Django); ASGI supports async and WebSockets (FastAPI)."],"xss":["XSS (Cross-Site Scripting)","An attack where malicious JavaScript gets onto your site and runs in other users' browsers. Prevented by escaping output and CSP."],"z_algorithm":["Algorithm","A finite, ordered set of steps that solves a problem or performs a task."],"z_annotation":["Annotation","A label starting with @ attached to code (`@Override`, `@Service`) that the compiler or a framework reads to change behavior."],"z_backend":["Backend","The part of an application that runs on servers: business logic, database access, security checks and APIs. Users never see it directly."],"z_behavioral":["Behavioral interview","Interview questions about how you acted in real past situations. Answer with a structured story such as STAR."],"z_bottleneck":["Bottleneck","The slowest or most limited component, which caps the performance of the whole system."],"z_browser":["Web browser","An app (Chrome, Firefox, Safari, Edge) that requests web pages from servers and displays them. It is the most common HTTP client."],"z_brute_force":["Brute force","Solving a problem by trying every possibility. Simple and correct, but often too slow for large inputs."],"z_bug":["Bug / debugging","A bug is a flaw that makes software behave wrongly. Debugging is finding and fixing its cause."],"z_cia":["CIA triad","The three goals of information security: Confidentiality, Integrity, Availability."],"z_client_side":["Client-side vs server-side","Client-side code runs on the user's device (usually the browser). Server-side code runs on a server and answers requests."],"z_cloud_provider":["Cloud provider","Company that rents computing resources over the internet. Largest: AWS, Microsoft Azure, Google Cloud."],"z_code_review":["Code review","A teammate reads your changes before they are merged, to catch problems and share knowledge."],"z_compiler":["Compiler","A program that translates source code into another form, for example Java source into bytecode, or TypeScript into JavaScript."],"z_crud":["CRUD","The four basic data operations: Create, Read, Update, Delete (SQL: INSERT, SELECT, UPDATE, DELETE)."],"z_data_structure":["Data structure","A way of organizing data in memory so that some operations are efficient: list, dictionary, set, stack, queue, tree, graph."],"z_data_type":["Data type","The kind of value: integer, decimal number, text (string), true/false (boolean), list, dictionary, and so on."],"z_database":["Database","An organized collection of data stored on disk so programs can search, update and share it safely."],"z_dbms":["DBMS","Database Management System: the software that stores the data and runs queries, such as PostgreSQL, MySQL or Oracle Database."],"z_deploy":["Deploy","Putting a version of the application on a server or cloud environment so it runs for real users (or testers)."],"z_devops":["DevOps","A combination of culture, practices and tools that brings development and operations together to deliver software faster and more reliably."],"z_entra":["Microsoft Entra ID","Microsoft's cloud identity and access service, formerly Azure Active Directory (Azure AD)."],"z_field_method":["Field / method","Fields store an object's data (state). Methods are the actions (behavior) the object can perform."],"z_firewall":["Firewall","A network control that allows or blocks connections based on rules (address, port, protocol)."],"z_framework":["Framework","Reusable foundation of code that gives structure to an application and calls your code at defined points (for example Spring Boot, Django, React)."],"z_frontend":["Frontend","The part of an application that runs on the user's device (browser or app) and that people see and interact with: layout, buttons, forms."],"z_ide":["IDE","Integrated Development Environment: an editor with extra tools such as autocomplete, a debugger and run/test buttons (IntelliJ IDEA, Eclipse, PyCharm)."],"z_indentation":["Indentation","Spaces at the start of a line. In Python they define which lines belong to a block (if, loop, function)."],"z_interpreter":["Interpreter","A program that reads source code and runs it directly. Python code runs with the `python` interpreter."],"z_jar":["JAR","Java ARchive: a ZIP-based file that bundles compiled classes and resources. Libraries and Spring Boot apps are shipped as JARs."],"z_java":["Java","A general-purpose, object-oriented programming language, very common in backend and enterprise software. Not related to JavaScript."],"z_k8s_terms":["Cluster / node / Pod","Cluster: the set of machines managed by Kubernetes. Node: one machine. Pod: smallest deployable unit, running one or more containers."],"z_library":["Library","A collection of reusable code that your program calls when it needs it (for example requests, Jackson)."],"z_linux":["Linux","Free, open source operating system family that runs most servers, containers and cloud machines."],"z_loop":["Loop","A structure that repeats a block of code, for example `for` (once per item) or `while` (as long as a condition is true)."],"z_lts":["LTS (Long-Term Support)","A release that receives updates and fixes for several years. Java 8, 11, 17, 21 and 25 are LTS versions."],"z_malware":["Malware","Malicious software: viruses, worms, ransomware, spyware and other programs designed to harm or steal."],"z_manual_vs_auto":["Manual vs automated testing","Manual: a person runs the steps and judges the result. Automated: code runs the checks quickly and repeatedly."],"z_markup":["Markup language","A language that labels content with tags to describe its structure or meaning, such as HTML. It is not a programming language: it has no logic."],"z_module":["Module / package","A module is a file of code you can import; a package is a folder of modules."],"z_monitoring":["Monitoring","Watching metrics (errors, latency, CPU) over time and alerting when the system is unhealthy."],"z_mvp":["MVP","Minimum Viable Product: the smallest version of a product that delivers value and lets the team learn from real users."],"z_nist_cloud":["NIST cloud characteristics","On-demand self-service, broad network access, resource pooling, rapid elasticity, measured service."],"z_nodejs":["Node.js","A JavaScript runtime that lets you run JavaScript outside the browser, for example to build servers and command-line tools."],"z_null_java":["null (Java)","The value of a reference that points to no object. Calling a method on it throws NullPointerException."],"z_object_storage":["Object storage","Storage for whole files (objects) accessed by key or URL, like Amazon S3 and Azure Blob Storage. Not a database."],"z_oop":["OOP","Object-oriented programming: organizing code into objects that bundle data (fields) and behavior (methods)."],"z_package":["Package (Java)","A namespace that organizes related classes and interfaces, like a folder: `java.util`, `com.mycompany.shop`."],"z_package_manager":["Package / dependency manager","A tool that downloads and tracks the libraries a project needs: Maven or Gradle (Java), pip (Python), npm (JavaScript)."],"z_parameter":["Parameter / argument","A parameter is a variable in a function's definition (`def greet(name)`). An argument is the value you pass when calling it (`greet(\"Ana\")`)."],"z_patch":["Patch","An update that fixes a bug or a security vulnerability in software."],"z_persistence":["Persistence","Keeping data after the program stops, by saving it on disk (for example in a database) instead of only in memory."],"z_pii":["PII","Personally Identifiable Information: data that can identify a person, such as name, email, ID number or address."],"z_pip":["pip","Python's package installer. It downloads packages from PyPI (the Python Package Index)."],"z_programming_language":["Programming language","A formal language for writing instructions that a computer can execute, such as Python, Java or JavaScript."],"z_qa":["QA","Quality Assurance: activities (testing, automation, process improvements) that help make sure software meets quality expectations."],"z_query":["Query","A request written for a database to get or change data, usually in SQL."],"z_region_az":["Region / Availability Zone","A Region is a geographic area; an Availability Zone is an isolated data center location inside it. Spread across AZs for high availability."],"z_server":["Server","A computer or a program that waits for requests from clients and sends back responses."],"z_stack":["Stack (tech stack)","The set of technologies used to build an application: for example React + Spring Boot + PostgreSQL."],"z_stakeholder":["Stakeholder","Anyone affected by or interested in a project: users, customers, managers, other teams."],"z_static_dynamic":["Static vs dynamic website","Static: the server sends the same ready-made files to everyone. Dynamic: the server builds the page for each request, usually with data from a database."],"z_system_design":["System design","Deciding the main components of a system and how they work together to meet requirements for scale, reliability and speed."],"z_tech_debt":["Technical debt","The future cost of quick or messy solutions taken now. It slows later changes until it is repaid."],"z_terminal":["Terminal / shell","The terminal is the text window; the shell (Bash, Zsh, PowerShell) interprets the commands you type."],"z_test_case":["Test case / test suite","A test case checks one scenario against an expected result. A suite is a group of test cases run together."],"z_ticket":["Ticket / issue","A tracked unit of work (bug, task, story) in a tool such as Jira, with owner, status and priority."],"z_trade_off":["Trade-off","A choice where improving one quality (speed) costs another (simplicity, consistency, money)."],"z_ui_ux":["UI / UX","UI (user interface) is what the user sees and uses. UX (user experience) is the whole experience of using the product."],"z_url":["URL","Uniform Resource Locator: the address of a resource, made of scheme (https), host (example.com), optional port, path (/products) and query (?id=7)."],"z_variable":["Variable","A name that refers to a value stored in memory, so the value can be used or changed later."],"z_vulnerability":["Vulnerability","A weakness in software, configuration or process that an attacker could exploit."]}}