Cloud Tech by Victor

Search

30 results for “recursion

Search results

Algorithms

Recursion & the Call Stack

Why CPython's recursion limit exists to protect the real, platform-dependent C stack rather than being an arbitrary language rule, and why raising it too high can still crash the interpreter instead of just allowing deeper recursion. Verified against CPython 3.12; exact stack behavior, default limit, and crash mode are interpreter- and version-specific, not universal across every Python implementation.

Recursion & the Call Stack

What does Python's recursion limit actually protect against, and is it just an arbitrary language-level rule?

It protects the real, underlying C stack the Python interpreter itself runs on, each level of recursion consumes real stack memory, and without a limit, sufficiently deep (or infinite) recursion would exhaust that stack and crash the interpreter process entirely, a hard C-level failure, not a clean Python exception. The limit converts that hard crash into a catchable `RecursionError` raised well before the actual stack is exhausted, which is exactly why it exists, a controlled failure mode is far better than an uncontrolled process crash, not an arbitrary restriction on how "should" write code.

Recursion & the Call Stack

Python's own documentation warns that raising the recursion limit "should be done with care, because a too-high limit can lead to a crash." Why doesn't raising the limit simply allow deeper, safe recursion?

The recursion limit is a proxy for the real constraint, actual available C stack space, which is platform-dependent and finite regardless of what the configured limit says. Setting the limit higher than the platform's actual available stack can support doesn't create more stack space, it just removes the early warning that would have raised a clean `RecursionError`, so recursion can now run deep enough to exhaust the real stack and crash the process with a low-level segmentation fault instead, a worse failure mode than the exception the limit was preventing in the first place.

Recursion & the Call Stack

Given the risk of hitting a recursion limit, when would you rewrite a recursive algorithm iteratively, and what does that actually trade away?

Rewrite iteratively when the recursion depth scales with input size in a way that could plausibly exceed the platform's real stack capacity, deep tree traversals, recursive descent over large or adversarial inputs, anything where "how deep" isn't bounded by a small constant. The trade is code clarity: many recursive algorithms (tree traversal, divide-and-conquer, backtracking) read far more naturally as recursion, mirroring the problem's own recursive structure, and converting them to an explicit-stack iterative version, while removing the depth risk entirely, usually costs some of that direct correspondence between code and problem structure.

Dynamic Programming

Why does a naive recursive Fibonacci function run in exponential time, and how does memoization fix that specifically?

Naive recursive `fib(n) = fib(n-1) + fib(n-2)` recomputes the exact same subproblem enormous numbers of times, `fib(n-2)` gets computed once directly and once again inside the `fib(n-1)` call, and this duplication compounds recursively, producing roughly 2^n total calls. Memoization caches each `fib(k)` result the first time it's computed, so every subsequent call with the same `k` becomes an O(1) cache lookup instead of a full recursive recomputation, collapsing the total distinct work down to O(n), one computation per distinct subproblem instead of an exponential number of repeated ones.

Rate Limiting Algorithms

A client sends a sudden spike of requests that exceeds the configured rate, but the API doesn't immediately reject any of them. Why not, and when does rejection actually start?

The token bucket has accumulated capacity up to the burst limit, if the client had been under the rate limit recently, unused tokens built up in the bucket, and that reserve absorbs a short spike without any request failing, exactly the point of separating burst capacity from steady-state rate. Rejection (a 429 response) only starts once the bucket is actually empty, every accumulated token has been consumed and the spike is sustained long enough that the rate of token consumption keeps exceeding the rate of token replenishment. This is why a token bucket, unlike a hard per-second cap, tolerates brief bursts gracefully while still enforcing a real steady-state ceiling.

Blog

How to Restrict USB and Removable Storage Devices using Group Policy in Active Directory

This lab documents a real world Group Policy implementation used to restrict USB drives, external hard drives, and all removable storage devices across domain joined systems in an Active Directory environment. The configuration addresses a critical security risk in modern on premises and hybrid env…

Database Connection Pooling

An application uses PREPARE to create a reusable prepared statement, then relies on it across multiple requests. What happens if it's deployed behind a transaction-pooled PgBouncer, and why?

It breaks. A SQL PREPARE statement is a session-level feature, it lives on whatever specific server connection issued the PREPARE, but transaction pooling reassigns the underlying server connection to a different client (or the same client's next transaction) as soon as each transaction ends, so there's no guarantee a later request lands on that same server connection where the prepared statement actually exists. This is explicitly documented as one of the session-based features transaction pooling breaks, along with SET/RESET, LISTEN, WITH HOLD cursors, and session-level advisory locks, all of which depend on state tied to one specific, persistent server connection. This is distinct from protocol-level named prepared statements issued via the extended query protocol (what most driver-level "prepared statements" actually are), which PgBouncer can support under transaction pooling when `max_prepared_statements` is set to a non-zero value.

LLM Fundamentals: Tokens, Context Windows & Sampling

A request's input already exceeds the model's context window before generation even starts. What happens, versus a request that only exceeds the limit once output is generated?

If the input alone already exceeds the context window, the API rejects the request upfront with a 400 error, generation never starts at all. If the input fits but input tokens plus the requested max output tokens could exceed the window, current models accept the request and generate as far as they can; if generation actually reaches the window limit before finishing, it stops early with a specific stop reason indicating the context window was exhausted, rather than silently truncating or erroring out mid-response. The distinction matters operationally: the first case is a fixable request-construction bug, the second is a signal to reduce the requested output length or the accumulated conversation history.

Algorithms

Graph Traversal: BFS & DFS

Why breadth-first search's queue explores every neighbor before any of their children, guaranteeing the shortest path in an unweighted graph, while depth-first search's stack (or recursion) does the opposite and can't make that guarantee at all.

Graph Traversal: BFS & DFS

What is the defining structural difference between BFS and DFS, and what data structure does each rely on?

Breadth-first search considers every neighbor of a vertex before considering any of those neighbors' own outgoing edges, per NIST's definition, extremes are searched last, which is implemented with a queue: vertices are processed in the order they were discovered, level by level outward from the start. Depth-first search does the opposite, it considers a vertex's outgoing edges (children) before any of the vertex's siblings, plunging as deep as possible along one path before backtracking, and NIST notes it's "easily implemented with recursion," which uses the call stack implicitly as its ordering structure (or an explicit stack in an iterative version).

Graph Traversal: BFS & DFS

For the same graph, why might you choose DFS over BFS even though BFS finds shortest paths and DFS doesn't?

Shortest-path guarantees aren't always the goal, DFS is a natural fit for exhaustively exploring all possibilities along one path before trying another (backtracking problems, detecting cycles, topological sorting, finding connected components), where the actual requirement is "visit everything reachable" or "explore this branch fully before trying the next," not "find the closest thing first." DFS via recursion is also often simpler to implement for these problems, at the cost of consuming call-stack depth proportional to how deep the graph goes, which matters for very deep or very large graphs where an iterative approach (or BFS) avoids the recursion-depth risk entirely.

Idempotency in Distributed Systems

Why does reusing the same idempotency key with different request parameters return an error instead of just processing the new parameters?

An idempotency key is a promise that a specific, exact operation happened once; if the same key showed up with different parameters, honoring the new parameters would silently violate that promise; either the original operation's recorded result no longer describes what the key represents, or the client made a mistake by rIeusing a key it should have generated fresh for a genuinely different request. Rejecting the mismatched reuse as an error, rather than guessing which parameters were "correct" or silently processing the new ones, surfaces that client-side mistake immediately instead of masking it.

Linux Users, Groups & sudo

Why does Linux split user information across /etc/passwd and /etc/shadow instead of keeping everything, including the password hash, in one file?

/etc/passwd has to be world-readable, ordinary tools and commands need to map UIDs to usernames and look up home directories or login shells for every user on the system. If password hashes lived there too, every local user could copy them out and run an offline cracking attempt. /etc/shadow holds the actual encrypted password (and related aging data) and is readable only by root, while /etc/passwd keeps a placeholder character (commonly `x`) in the password field, preserving the UID-lookup functionality everything else depends on without exposing anything crackable.

PostgreSQL Fundamentals

Why does wrapping several statements in `BEGIN`/`COMMIT` matter, even for a multi-step operation that's logically one action?

Without an explicit transaction, PostgreSQL commits each statement independently the moment it succeeds; if a multi-step operation (debit one account, credit another) fails halfway through, the database is left in an inconsistent, partially-applied state with no way to undo the completed step. Wrapping the statements in `BEGIN`/`COMMIT` groups them so they can be committed or rolled back together, but that alone isn't automatic protection against every failure mode: PostgreSQL only aborts a transaction on its own when a statement raises an actual SQL error, an `UPDATE` that runs successfully but matches zero rows (a mistyped account id, for instance) is not an error at all, and would otherwise be committed as if the transfer had actually happened. Making the transaction genuinely safe means checking that each `UPDATE` affected exactly the one row expected and issuing an explicit `ROLLBACK` if either check fails, only issuing `COMMIT` once both checks pass.

React Hooks Deep Dive

Why does React require hooks to be called in the same order on every render?

React does not track hook state by name; it tracks it by call order in a linked list attached to the component's fiber. On each render, React walks that list and matches the nth useState call to the nth stored slot. If a hook is called conditionally (inside an if, or after an early return), the call order can shift between renders, and React ends up reading the wrong slot for a given hook; this is exactly why hooks cannot be called inside conditionals or loops.

React Rendering & Reconciliation

Does React mutate the DOM during the render step, and if not, when does the actual DOM update happen?

No. Rendering is a pure calculation, React calls component functions to figure out what the new JSX should be and diffs it against the previous render, but no DOM node is touched during this step. The actual DOM update happens in a separate commit step afterward, where React applies only the minimal necessary changes based on what actually differs from the previous render, appending everything on the very first render, but patching selectively on every re-render after that. This separation is why an uncontrolled `<input>`'s typed value survives a re-render of its parent: React only touches DOM nodes that actually changed, and leaves everything else alone.

Sorting Algorithms & Stability

An O(n^2) sort can be faster than an O(n log n) sort for small inputs. Why, and why doesn't that matter for a general-purpose sort function?

Big O describes asymptotic growth, not actual runtime, and O(n^2) algorithms often have smaller constant factors and simpler inner loops (no recursion or merge-buffer overhead) that make them genuinely faster in wall-clock time for small n, even though the more sophisticated O(n log n) algorithm would eventually win as n grows. This is exactly why production sort implementations, including Timsort, special-case small subarrays with a simple insertion sort internally rather than using the full merge-sort machinery on tiny inputs, getting the best of both regimes instead of picking one algorithm for every input size.

SQL Injection Prevention

Why does string escaping alone not fully prevent SQL injection?

Escaping tries to neutralize special characters (like quotes) so user input cannot break out of its intended string literal, but it is easy to get wrong, different databases and contexts (string literals, numeric contexts, identifiers, LIKE patterns) have different escaping rules, and a single missed case reopens the vulnerability. Parameterized queries avoid the problem entirely: user input is sent to the database separately from the query structure, so it can never be interpreted as SQL syntax regardless of its content.

Blog

How to Configure Secure File System Management with NTFS Permissions and Mapped Drives in a Windows Server Domain (Lab Guide)

This lab demonstrates how to design and implement secure file system management in a domain environment using Active Directory, Windows Server 2019, and Hyper V. The focus is on enterprise style file sharing, using NTFS permissions, group based access control, and mapped network drives, all aligned…

Cloud Service Models

Why might a team deliberately choose IaaS over PaaS even though PaaS requires less operational work?

PaaS trades control for convenience; it constrains you to whatever runtimes, configurations, and scaling behavior the platform supports. Teams choose IaaS when they need capabilities a PaaS doesn't expose (custom OS-level tuning, unusual networking topologies, specific compliance requirements that mandate control over the underlying host), when they're running workloads a PaaS wasn't designed for, or when the cost model of many small PaaS instances doesn't make sense at their scale compared to self-managed infrastructure.

Consistent Hashing

Why does a real ring hash implementation give each host many positions on the ring instead of just one, and what problem would a single position per host cause?

A host thrown onto the ring at just one point can end up, purely by chance, owning a disproportionately large or small arc of the ring if the hash values happen to land unevenly, since with few points there's no averaging effect smoothing out the randomness. Assigning each host many positions on the ring, scaled by that host's intended weight, so a double-weight host gets roughly twice as many ring entries as a single-weight one, averages out that randomness across many smaller arcs per host, producing a much more even overall traffic distribution than a single coin-flip-like placement per host would.

Database Replication

A PostgreSQL primary crashes right after committing a transaction, under asynchronous replication. Is that transaction guaranteed to exist on the standby?

No. Asynchronous replication (the default) confirms a commit on the primary without waiting for the standby to receive or apply the corresponding WAL records, there's typically a small delay, often under a second, between a commit and its visibility on the standby. If the primary crashes in that window, before the WAL records reached the standby, that transaction is lost even though the client was already told it committed successfully. This is the specific, documented risk asynchronous replication accepts in exchange for not adding network round-trip latency to every commit.

Hash Tables & the Hash/Equality Contract

What is the required contract between equality and hashing for an object used as a dictionary key, and why does the hash table need it specifically?

The contract is one-directional but strict: if two objects compare equal, they must produce the same hash value. A hash table uses an object's hash to pick which bucket to look in, then uses equality only to confirm the exact match within that bucket, so if two equal objects hashed differently, a lookup for one would search the wrong bucket entirely and never even reach the equality check that would have confirmed the match. The hash doesn't have to be unique across unequal objects (collisions are expected and handled), it just has to agree for anything that compares equal, that's the one property the whole lookup mechanism depends on.

Blog

Building Golden Images with Azure Compute Gallery: Custom VM Image Creation & Deployment (Hands-On Lab)

A step-by-step Azure lab for creating, versioning, and deploying standardized VM images at scale.

Azure Fundamentals

What is the difference between a resource group and a subscription in Azure?

A subscription is a billing and access-management boundary; it's tied to an agreement with Microsoft, has its own spending limits and quotas, and is typically the unit organizations use to separate environments (production vs. non-production) or business units. A resource group is a logical container inside a subscription that groups related resources (a VM, its disks, its network interface) that share the same lifecycle, created and deleted together. Deleting a resource group deletes everything in it, which makes resource groups the practical unit of "this is one deployable thing," while subscriptions are the practical unit of "this is one billing and governance boundary."

Database Connection Pooling

Why would you choose session pooling over transaction pooling even though it scales to fewer concurrent clients per server connection?

Session pooling is the only mode of the two that supports every PostgreSQL feature without exception, prepared statements, session variables set via SET, LISTEN/NOTIFY, session-level advisory locks, because the server connection genuinely stays with the client for as long as their session lasts. If an application depends on any of those session-level features and can't be refactored around them, session pooling is the correct choice despite its lower connection-reuse efficiency, trading raw scalability for full feature compatibility rather than working around broken session state.

Database Locking & Deadlocks

Two transactions each update two of the same two accounts, but in opposite order, and deadlock. What's the actual fix, not just for this pair of transactions, but for the application generally?

The deadlock happens because Transaction 1 locks account A then waits for account B, while Transaction 2 locks account B then waits for account A, a circular wait. The general fix isn't retry logic alone, retries only paper over deadlocks that keep recurring, it's acquiring locks on multiple objects in the same, consistent order everywhere in the application (for example, always locking accounts in ascending id order), which makes the circular-wait pattern structurally impossible rather than merely less frequent. Retry logic is still worth having as a safety net, but consistent lock ordering is what actually eliminates this class of deadlock.

Linux Networking

A socket shows up in the LISTEN state versus ESTABLISHED. What is actually different about what that socket is doing?

LISTEN means a server-side socket is bound to a port and passively waiting to accept incoming connection requests, it isn't attached to any specific remote peer yet. ESTABLISHED means a full connection has completed its handshake and is actively associated with a specific remote address and port, data can flow in both directions. Seeing a service you expect to be running not show a LISTEN socket on its expected port is usually the very first, most direct signal that the service isn't actually up or isn't bound where you think it is.

SQL Injection Prevention

What is the difference between a parameterized query and simply concatenating a sanitized string?

A parameterized query sends the SQL command and the user-supplied values as two separate things to the database driver, the driver (or the database itself, for prepared statements) binds the values into the query plan without ever treating them as part of the SQL text. String concatenation, even "sanitized," still builds one text string where user input and SQL syntax share the same channel, any gap in the sanitization logic can be exploited. Parameterization removes that shared channel entirely rather than trying to police it.

Search results for “recursion” | Cloud Tech by Victor