Web Development Interview Questions for 7 Years Experience
40 questions with answers for candidates with 7 years of experience — 1 easy, 14 medium, 25 hard.
What interviewers expect: 7 years experience
Seven-year candidates are expected to lead teams and projects. Questions cover technology selection, migrating legacy PHP applications, cloud hosting choices, observability, cost control and engineering standards. You should show examples of improving delivery speed and stability across a team, not just your own code.
This set is weighted towards Hosting and Deployment (9), MySQL Database (7), Web Security (6), DOM and Browser Events (6).
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
Limit failed login attempts to stop brute-force attacks.
Track failures per account and IP, then block temporarily:
$stmt = $pdo->prepare('SELECT COUNT(*) FROM login_attempts
WHERE ip = ? AND attempted_at > NOW() - INTERVAL 15 MINUTE');
$stmt->execute([$_SERVER['REMOTE_ADDR']]);
if ($stmt->fetchColumn() >= 5) {
http_response_code(429);
exit('Too many attempts. Try again in 15 minutes.');
}
// on failure
$pdo->prepare('INSERT INTO login_attempts (ip, attempted_at) VALUES (?, NOW())')
->execute([$_SERVER['REMOTE_ADDR']]);
Add CAPTCHA after a few failures and offer two-factor authentication.
When vertical margins of adjacent block elements touch, they merge into a single margin equal to the larger one instead of adding up. It also happens between a parent and its first or last child when no padding, border or block formatting context separates them. Margins do not collapse in flex or grid containers. Developers often avoid surprises by using padding, gap or margin in one direction only.
03
A cart total shows 0.30000000000000004 instead of 0.3. Why, and how do you fix it?
JavaScript numbers are IEEE 754 floating point, so decimals like 0.1 and 0.2 cannot be stored exactly. For money, I would store and calculate amounts in the smallest unit, such as paise as integers, and convert only for display using Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }). The server should always recalculate the final amount, because client-side totals cannot be trusted for payment.
04
Open and close an accessible modal using the native dialog element.
The dialog element handles focus and the Escape key for you:
<button id='open'>Enquire now</button>
<dialog id='enquiry'>
<form method='dialog'>
<p>Thank you for your interest.</p>
<button>Close</button>
</form>
</dialog>
<script>
const dlg = document.getElementById('enquiry');
document.getElementById('open').addEventListener('click', () => dlg.showModal());
</script>
showModal places it in the top layer with a backdrop, and form method='dialog' closes it without a request.
XSS lets an attacker run their JavaScript in another user's browser. Stored XSS saves the payload in the database, such as a malicious comment shown to every visitor. Reflected XSS bounces a payload from a URL parameter straight into the response. DOM-based XSS happens entirely in client code, for example writing location.hash into innerHTML. Defences are context-aware output escaping, safe DOM APIs and a Content Security Policy.
JavaScript runs on a single main thread with a call stack. Asynchronous work like timers, network requests and events is handled by browser APIs, and their callbacks are queued. After the stack is empty, the event loop first runs all microtasks, such as promise callbacks and queueMicrotask, then takes the next macrotask, such as a setTimeout callback. That is why a resolved promise logs before a setTimeout of 0.
07
Lighthouse shows a poor Largest Contentful Paint caused by the hero image. What steps do you take?
First I would compress the image and serve it in AVIF or WebP at the correct size using srcset. I would remove loading='lazy' from it, add fetchpriority='high' and a preload link in the head, and make sure it is in the initial HTML rather than injected by JavaScript. I would also serve it from a CDN and check that render-blocking CSS is not delaying the paint.
08
How have you helped a junior developer learn deployment?
Situation: a new joiner was nervous about deploying to production. Task: I was asked to make them independent within a month. Action: I wrote a step-by-step deployment checklist, let them deploy to staging while I watched, then paired on two production releases with them driving. Result: they handled releases alone after three weeks and later improved our checklist with a rollback section.
A transaction groups several SQL statements so they succeed or fail together. ACID means Atomicity, all or nothing; Consistency, rules and constraints stay valid; Isolation, concurrent transactions do not see each other's partial changes; and Durability, committed data survives crashes. For example, transferring wallet balance debits one row and credits another inside START TRANSACTION and COMMIT, with ROLLBACK if anything fails.
10
Compare BEM and utility-first approaches to CSS architecture.
BEM names classes as block__element--modifier, such as card__title--large, which keeps styles scoped and readable in large codebases. Utility-first frameworks like Tailwind CSS compose small single-purpose classes in the markup, which speeds up development and avoids growing stylesheets. BEM gives cleaner HTML, utilities give consistency and smaller final CSS after purging. The right choice depends on team size, design system and tooling.
Show the same message whether or not the email exists to avoid account enumeration. Generate a long random token with random_bytes, store only its hash with a short expiry such as 30 minutes, and email a one-time link. On reset, verify the hash and expiry, set the new password with password_hash, delete the token and invalidate existing sessions. Rate-limit the request endpoint to prevent email flooding.
12
Your site suddenly shows 502 Bad Gateway. How do you troubleshoot it?
502 means Nginx could not get a valid response from the upstream, usually PHP-FPM or an application server. I would check if the service is running with systemctl status php8.3-fpm, read the Nginx error log and the PHP-FPM log, and confirm the socket path in the config matches. Common causes are crashed workers, exhausted pm.max_children, memory limits or a recent config change. Restarting brings it back, but the root cause must be fixed.
13
Create a GitHub Actions workflow that deploys on every push to main.
Group by month and sum the amounts:
SELECT DATE_FORMAT(created_at, '%Y-%m') AS month,
COUNT(*) AS orders,
SUM(amount) AS revenue
FROM orders
WHERE created_at >= '2026-01-01'
AND created_at < '2027-01-01'
AND status = 'paid'
GROUP BY month
ORDER BY month;
Using a date range instead of YEAR(created_at) = 2026 lets MySQL use an index on created_at.
Check errors, size and real MIME type, then store with a random name:
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK && $_FILES['photo']['size'] < 2_000_000) {
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($_FILES['photo']['tmp_name']);
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
if (isset($allowed[$mime])) {
$name = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__ . '/uploads/' . $name);
}
}
Never trust the original filename or extension.
16
The page stutters while scrolling because of a scroll event handler. How do you fix it?
Scroll events fire many times per second, so heavy work in the handler blocks the main thread. I would throttle the handler or batch DOM writes inside requestAnimationFrame, mark listeners as { passive: true }, and avoid reading layout properties like offsetTop after writing styles. For tasks like lazy loading, sticky effects or reveal animations, I would replace the handler with IntersectionObserver or CSS position: sticky.
17
Users report being redirected to a gambling site from your pages. What do you check?
This often comes from injected JavaScript or a compromised third-party script. I would check the page source and Network tab for unfamiliar scripts, inspect .htaccess for malicious rewrite rules, search the database and theme files for obfuscated code like base64_decode or eval, and review recently changed files on the server. A strict CSP and Subresource Integrity on CDN scripts help prevent repeat incidents.
18
A client wants to move a growing site from shared hosting to a VPS. How do you plan the migration?
I would set up the VPS with Nginx, PHP-FPM, MySQL, firewall and SSL, matching PHP versions and extensions. Then I would copy files with rsync, export and import the database, and test the site using a hosts file entry before touching DNS. After lowering the TTL, I would do a final data sync during low traffic, switch DNS, monitor logs, and keep the old hosting live for a few days as fallback.
19
What is the difference between Promises and async/await?
A Promise represents a value that will be available later, handled with then and catch chains. async/await is syntax built on promises: an async function always returns a promise, and await pauses that function until the promise settles, making code read top to bottom. Errors are handled with try and catch. For parallel work you still use Promise.all, because awaiting calls one by one runs them sequentially.
20
What is CORS and why does the browser block some API calls?
The same-origin policy stops scripts on one origin from reading responses from another origin. CORS is how a server opts in: it returns headers like Access-Control-Allow-Origin naming allowed origins. For non-simple requests, such as JSON with custom headers, the browser first sends an OPTIONS preflight. CORS is enforced only by browsers, so it is not a security control for the server itself, and Allow-Origin * should never be combined with credentials.
An iterator is an object with a next() method returning { value, done }, and any object with a Symbol.iterator method can be used in for...of loops and spread syntax. A generator function, written function*, creates iterators easily: each yield pauses execution and returns a value, resuming on the next call. Generators are useful for lazy sequences, such as paginated API results, without building huge arrays in memory.
22
Pagination becomes very slow on later pages. Why, and how do you fix it?
LIMIT 20 OFFSET 100000 forces MySQL to read and discard 100,000 rows before returning 20, so deep pages get slower. Keyset or cursor pagination fixes this: remember the last seen id and query WHERE id < :last_id ORDER BY id DESC LIMIT 20, which uses the index directly. It suits infinite scroll and APIs. For numbered pages, limiting maximum depth or caching counts also helps.
23
Your page has a high Cumulative Layout Shift because of fonts and ads. How do you reduce it?
For fonts I would preload the main font file, use font-display: swap or optional, and tune fallback fonts with size-adjust so the swap does not move text. For ads and embeds I would reserve space with a fixed min-height or aspect-ratio box before they load. I would also set width and height on all images and avoid inserting banners above existing content after load.
24
What are container queries and how do they differ from media queries?
Media queries respond to the viewport size, while container queries respond to the size of a parent element. You mark a parent with container-type: inline-size and then write @container (min-width: 400px) rules for its children. This lets a card component change layout depending on whether it sits in a narrow sidebar or a wide main area, making components truly reusable. They are supported in all modern browsers.
25
Rendering a table with 5,000 rows freezes the browser. What are your options?
Creating thousands of nodes at once blocks the main thread. Options are server-side pagination, rendering in chunks with requestAnimationFrame, or virtual scrolling where only the 30 to 50 visible rows exist in the DOM at any time. I would also build rows in a DocumentFragment, avoid layout reads inside loops, and use CSS content-visibility: auto so off-screen rows skip rendering work.
26
Implement infinite scroll using IntersectionObserver.
Observe a sentinel element at the bottom of the list:
const sentinel = document.querySelector('#sentinel');
let page = 1, loading = false;
const observer = new IntersectionObserver(async ([entry]) => {
if (!entry.isIntersecting || loading) return;
loading = true;
const res = await fetch('/api/posts?page=' + (++page));
const posts = await res.json();
if (!posts.length) observer.disconnect();
posts.forEach(renderPost);
loading = false;
}, { rootMargin: '200px' });
observer.observe(sentinel);
It is far cheaper than listening to every scroll event.
An A record maps a domain to an IPv4 address and AAAA to IPv6. CNAME points one name to another, such as www to example.com, but cannot sit on the root domain. MX records route email to mail servers. TXT records hold verification and email security data like SPF, DKIM and DMARC. NS records name the authoritative nameservers. TTL controls how long resolvers cache each record.
InnoDB is the default MySQL storage engine. It supports transactions, row-level locking, foreign keys and crash recovery, making it suitable for almost all applications. MyISAM uses table-level locking, has no transactions or foreign keys, and can corrupt on crashes. MyISAM was once faster for read-only workloads, but modern InnoDB matches or beats it. Old tables still on MyISAM should usually be converted.
29
How do you manage configuration and secrets across local, staging and production?
I keep code identical across environments and change only configuration through environment variables, usually loaded from a .env file that is never committed. A .env.example documents required keys without values. In production, secrets live in the server environment, the CI secret store or a cloud secrets manager. Each environment has separate database credentials and API keys, so a staging leak cannot affect production.
30
Write an Nginx server block for a PHP application using PHP-FPM.
I would autosave the form into sessionStorage or localStorage on input with a small debounce, then restore values on page load and clear them after successful submission. A beforeunload warning can ask users to confirm leaving when there are unsaved changes. Sensitive fields like passwords or card details must never be saved. For multi-step forms, saving drafts on the server is more reliable.
32
How do arrow functions differ from regular functions?
Arrow functions have shorter syntax, an implicit return for single expressions, and no own this, arguments or super; they inherit these from the outer scope. They cannot be used as constructors with new and do not have a prototype property. This makes them ideal for callbacks like array.map, but unsuitable for object methods that need this to refer to the object, or for event handlers that rely on this as the element.
33
How do indexes work and when can they hurt performance?
InnoDB indexes are B+ trees that let MySQL find rows without scanning the whole table, which speeds up WHERE, JOIN and ORDER BY on indexed columns. A composite index follows the leftmost prefix rule. Indexes cost extra disk space and slow down INSERT, UPDATE and DELETE because each index must be updated. Low-selectivity columns like gender rarely benefit, and functions on columns in WHERE can stop index use.
34
A results website expects ten times normal traffic on announcement day. How do you prepare?
I would load test with tools like k6 or JMeter to find the breaking point, then cache result pages aggressively using a CDN and Redis. The database should have proper indexes, and read-heavy queries could go to replicas. On cloud, I would configure auto-scaling and pre-warm extra instances before the announcement. A lightweight static fallback page and a queue for heavy tasks keep the site responsive under peak load.
35
Your application logs show frequent deadlock errors. What do you do?
A deadlock happens when two transactions each hold a lock the other needs; InnoDB kills one. I would read SHOW ENGINE INNODB STATUS to see the conflicting queries. Fixes include accessing tables and rows in a consistent order, keeping transactions short, adding indexes so updates lock fewer rows, and avoiding user interaction inside a transaction. The application should also retry the failed transaction once or twice.
Place these in the server block:
add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains' always;
add_header X-Content-Type-Options 'nosniff' always;
add_header Referrer-Policy 'strict-origin-when-cross-origin' always;
add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; frame-ancestors 'none'" always;
add_header Permissions-Policy 'camera=(), microphone=()' always;
Start CSP in Content-Security-Policy-Report-Only mode to find what breaks before enforcing it.
37
Explain the critical rendering path and how HTML structure affects it.
The browser parses HTML into the DOM, CSS into the CSSOM, combines them into a render tree, then calculates layout and paints pixels. CSS in the head is render-blocking and synchronous scripts block parsing, so their placement decides how fast the first paint appears. Good practice is to inline small critical CSS, defer non-essential scripts, preload key fonts and hero images, and keep the initial HTML lean.
38
Someone accidentally ran DELETE without a WHERE clause on production. How do you recover?
First I would stop writes to that table to avoid further damage and inform the team. Then I would restore the latest backup to a separate server and, if binary logging is enabled, replay binlog events up to just before the bad statement using mysqlbinlog for point-in-time recovery. Finally I would copy the recovered rows back. Afterwards I would enable safe-updates mode and restrict production access.
39
What is the difference between reflow and repaint?
Reflow, or layout, happens when the browser recalculates positions and sizes, triggered by changing width, adding elements, or reading offsetHeight after a write. Repaint happens when only visual styles like colour or background change. Reflow is more expensive and can cascade to the whole page. Animating transform and opacity avoids both because they are handled by the compositor, which keeps animations smooth at 60 frames per second.
40
What are the differences between Apache and Nginx?
Apache uses a process or thread based model and supports per-directory .htaccess files, which is convenient on shared hosting. Nginx uses an event-driven model that handles many concurrent connections with low memory, making it excellent for static files and as a reverse proxy. Nginx runs PHP through PHP-FPM and has no .htaccess, so rules go in central config. Many setups put Nginx in front of Apache or application servers.
Frequently asked questions
What is asked in Web Development interviews for 7 years of experience?
Seven-year candidates are expected to lead teams and projects. Questions cover technology selection, migrating legacy PHP applications, cloud hosting choices, observability, cost control and engineering standards. You should show examples of improving delivery speed and stability across a team, not just your own code.
How many questions should I practise before a Web Development interview?
Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.
Which topics matter most for 7 years of experience?
Focus first on Legacy migration, Cloud architecture, Engineering standards, Stakeholder management.