text:
By Martin Crutsinger
AP Economics Writer
WASHINGTON (AP) -- The U.S. economy appears to be weaker than many economists had thought after a report Monday showed consumers spent cautiously in June at retail businesses.
Americans bought more cars and trucks, furniture and clothes. But they cut back almost everywhere else. They spent less at restaurants and bars, reduced purchases at home improvement stores, and bought fewer computers and electronics.
Overall retail spending rose 0.4 percent in June from May, the Commerce Department said. But excluding volatile spending on autos, gasoline and building supplies, so-called core retail sales rose just 0.15 percent. That's the weakest gain since January.
Economists said the deceleration in retail sales could slow economic growth in the April-June quarter to an annual rate below 1 percent. That's weaker than many had thought and would be down from a tepid 1.8 percent rate in the January-March quarter.
Still, many economists aren't changing their forecast for the second half of the year. Most expect growth will rebound to around a 2.5 percent rate.
"Job growth, income growth, rising stock prices and higher home prices all suggest a healthier state for the household sector in the second half of the year," said Paul Dales, chief U.S. economist at Capital Economics.
Consumers are still increasing their spending. But their pace has dropped off sharply from the start of the year. Core retail sales increased from April through June at a 2.7 percent annual rate. That's down from a 4.2 percent rate during the first three months of the year.
The decline suggests an increase in Social Security taxes that took effect Jan. 1 may be starting to squeeze consumers. And that's slowing growth because consumers' spending accounts for about 70 percent of economic activity.
Other reports Monday added to worries that growth had weakened in the second quarter. Businesses increased their stockpiles only slightly in May, signaling fewer orders of factory-made goods.
And economic growth in China slowed in the April-June quarter to its lowest rate in more than two decades. That could reduce demand U.S. exports.
Dales, however, said the risk is low because China makes up only 7 percent of America's total market. The bigger threat to the U.S. economy is if dampened growth in China spreads to other nations that buy more U.S. goods.
Most analysts expect U.S. economic growth to bounce back in the second half of the year. The biggest reason for their optimism is an improving job market that should help offset the drag from the tax increase.
Employers have added an average 202,000 jobs a month this year, up 180,000 in the previous six months. Stronger job gains should increase overall income and boost consumers' spending.
Economists also point to a housing recovery that continues to gain momentum. That's lifting home prices, making Americans feel wealthier and more likely to spend. It's also adding construction jobs.
"Retail sales will continue to grow at a moderate clip, as gains in disposable income stemming from moderate job creation outweigh the lingering effects of payroll tax increases," said Martin Schwerdfeger, senior economist at TD Economics.
There were some encouraging signs in the retail sales report that consumers remain confident in the economy. Spending on cars and trucks rose 1.8 percent -- the biggest gain since November. And furniture sales jumped 2.4 percent last month. Both gains show many consumers are still making large purchases.
Over the past year, car and truck sales have risen 11.4 percent, according to the government's data. That shows autos remain the most vibrant part of the retail economy.
Earlier this month the nation's automakers also reported robust sales in June. Sales totaled 7.8 million from January through June, the best first half since 2007. And the outlook for the rest of 2013 is just as strong. Wider credit availability and hot-selling new vehicles are helping to boost sales. Demand for big pickups has been a key factor in higher sales.
Monday's government report comes after some retail chains reported their best sales gains since January. Revenue at stores opened at least a year rose 4.1 percent in June compared with the same month a year ago, according to a preliminary tally of 13 retailers by the International Council of Shopping Centers.
June is typically when stores clear out summer merchandise to make room for fall goods. Brisk sales mean that stores probably won't be stuck with piles of summer clothes that need to be cleared as back-to-school sales kick off in late July.
Published: Wed, Jul 17, 2013


text:
- Insurance
- Vetting
- Replacement cleaners if needed
- Travel included
- Any reasonable task
- The same cleaner every session
- At least 2 hours per session
- Weekly or every 2 weeks
Gunness Cleaners: Simply call Jim on 0800 112 3631 or send us an email: firstname.lastname@example.com
*If you are not satisfied with your cleaning, you can claim your agency fee back for the last session.
This is not the cleaner's salary, but the agency fee. Valid for 3 times maximum. New clients only.
I have used Nationwide Cleaners for over a year and have had the same cleaner. Adriana is extremely reliable and professional. She does an excellent job. Nationwide also easily arranged for a substitute cleaner, at my request, when Adriana was away on holiday for a week. Thank you Nationwide Cleaners for making my life easier!!!
Adrienn is extremely reliable and flexible, swapping days without any fuss on the odd occasion we need to rearrange. She has the place looking clean and tidy in just a couple of hours, without breaking a sweat - quite a feat in a townhouse when having to haul a Dyson up and down all those stairs! She is also happy to add additional tasks to her regular workload (oven-cleaning - yuk) when required. I wouldn't hesitate to recommend her to any new clients.
Since I joined Nationwide cleaners Adriana has cleaned the House. At the beginning it needed a really good clean, resulting in her doing extra time on her first 2 visits, but now she has mastered it & keeps it spic & span. She is very reliable & professional in her job & I would recommend her to any new clients.
My cleaner has been very reliable and does a good job. The office staff are polite and helpful.
Please note that JDP Cleaners Ltd trading as Nationwide Cleaners Lincolnshire, company number 10982647, whose registered office is at 13 Queensway, Skellingthorpe, Lincoln, LN6 4RJ is a licensee of the Nationwide Cleaners franchise and is independently owned and operated. Nationwide Cleaners Ltd and/or Nationwide Cleaners (Franchising) Ltd are not responsible for the contents of any advertisement or any action or omission of the franchisee.

subset: commoncrawl


text:
Trussville, Alabama Business Insurance
At Huffstutler Insurance Group, Inc., we pride ourselves in evaluating your business insurance needs in Trussville, Alabama. We take the time to find out the different challenges your industry may have for insurance concerns and tailor a package that fits your risks. We also look at other exposures your business may have according to your personnel, location and future plans.
Our top-rated companies work with local businesses as well as global providers to ensure even the worst disaster won't affect your business adversely.


text:
Advanced Search |
Search Tips
Click the button below to add the Bleasdale Sparkling Shiraz to your wish list.
Minimum Order 12 bottles
If you really want to buy less or buy mix cases, please contact us.
Free Shipping for Some Metro Areas, Contact Us to Waive Cost
All prices are in AUD.
Copyright 2023 Tony's Cellars.
Sitemap |
Terms and Conditions |
Powered by mshShoppingCart by myshophosting.
It is against the law to sell or supply alcohol to, or obtain alcohol on behalf of, a person under the age of 18 years.Liquor License Number: LIQP700382708


text:
Over 3 million pictures framed
- Help & Support
Style & Ideas
Get Inspiration
- For Business
Item added to your basket
This brown frame has been designed to fit 4 x 6 inch (10x15cm) size pictures making it perfect for showcasing standard size artwork and photographs. The stylish wood moulding has a 20mm face width and is 12mm deep.
Nielsen Bainbridge has a proud history driven by the highest standards in product design and production quality. Their extensive collection of beautiful off-the-shelf frames offer both value and quality.


text:
Govt (Sarkari) Jobs
Top Company Jobs
Today Trending Jobs
Engineering Jobs
Medical Jobs
Jobs by Education
Jobs by Roles
Jobs by States
Jobs by Locations
Exam Results
Admit Card
Answer Keys
View All
|Join our Whatsapp Group to Get Latest Update Alerts
|AIIMS Kalyani - Walk in for Senior Resident Posts
|BECIL - Apply Online for OT Technician, ICU Technician Posts
|ESIC - Walk in for 11 Specialist, Medical Officer Posts
|JKSSB - Apply Online for 201 Supervisor Posts
|IOCL - Apply Online for 1603 Apprentice Posts
|Income Tax Department - Apply Online for 55 Multi Tasking Staff, Inspector of Income Tax, Stenographer Grade II, Tax Assistant Posts
|BESCOM - Apply Online for 400 Apprentice Posts
|DCPU - Apply for Various Cleaner Posts
|NTPC - Apply Online for 70 Apprentice Posts
|NTPC - Apply Online for 114 Instructor, Surveyor, Supervisor, Mining Sirdar, Overman Posts
Get All Latest Update Alerts - Join our Groups in Whatsapp | Telegram | Google News
Design Instructor Jobs 2023: Apply for current active job openings for Design Instructor Post for both fresher and experienced candidates across India updated on 12-12-2023. Discover all current Design Instructor Job vacancies for your qualification and find the active openings of Design Instructor Jobs 2023 in your Location. This Design Instructor Jobs 2023 page contains the information such as organization name, total vacancy, post title, eligibility, job location, last date, etc. Aspirants who are seeking for Design Instructor Jobs can get the all latest job availability from this page. Moreover, Candidates may join our official telegram channel and also bookmark this page to know the latest and upcoming Design Instructor Jobs 2023 instantly.
Last Modified: 12-12-2023
More than job openings are currently active for Design Instructor designations from Government sectors like SSC, UPSC, State PSC, PSU, Agriculture Jobs, Railway jobs, Banking, Defence, Private Colleges, Financial Institutions, Teaching Jobs, Faculty jobs in various Universities and Schools as well as Private jobs and many more. Below list contains the current active job openings for Design Instructor roles across India.
Are you looking for Design Instructor jobs in India? Yes, you're at the right place. Candidates can get the latest Design Instructor jobs from here. Check our page regularly in order to grab all the latest Design Instructor jobs based on your designation requirements. Design Instructor Jobs 2023 are updated along with the basic information's like educational qualification, salary, age limit, selection procedure, application fee, exam fee, application procedure and more. Instantly get upcoming Central and State Government related job openings based on your designations from various sectors like Railway, SSC, UPSC, State PSCs, PSUs, Bank, Defence, Indian Navy, and Air Force Jobs.
"Design Instructor Jobs 2023"
"Design Instructor Careers"
"Design Instructor Sarkari Naukri"
"Design Instructor Job Vacancy"
"Design Instructor Job Openings"
"Latest Design Instructor Notification 2023"
"Design Instructor Fresher Jobs 2023"
"Design Instructor Recruitments 2023"
"Job Openings for Design Instructor Post"
You all must have this kind of questions in your mind. This page will solve this puzzle of yours. Just take a look.
Job seekers who are in search of Design Instructor related jobs from different sectors like State Government, Central Government and Private Organizations across India can be getting their job easily through Jobskar. Candidates can visit our website and can click Jobs by designation/role tab and they can check all the latest and new active jobs available for Design Instructor Post 2023 in that page regularly.
Here you can find the latest Design Instructor Jobs according to your preferred location instantly based on State-wise and Location-wise we listed. In this page, you can quickly know the new and all upcoming Design Instructor Jobs in various popular cities like New Delhi, Mumbai, Bangalore, Chennai, Kolkata, Hyderabad, Pune, Noida, Gurgaon, Chandigarh, Ahmedabad, Agra, Jaipur, Kochi, Lucknow, Bhubaneshwar and many more.
This page also contains all the walk-in interview notification for Design Instructor posts across various locations in India. Every day in this page, you can find large number of walk-in jobs for various positions recruited by many Top companies in India. According to your interest you can choose and apply for the walk-in interview job from this page.
Latest Design Instructor Jobs 2023 are updated every day here. There are many different types of designations are available such as Sales Engineer, Personal Secretary, Marketing Manager, Administrative Design Instructor, Company Secretary, Area Manager, General Managers, Radiologist, Supervisor, Data Analyst, Radio Jockey, Legal Manager, Air Hostess, Network Engineer, Clerk, Medical Lab Technician, Hospital Pharmacist, Network Security Administrator, Computer Teacher, Security Design Instructor, Engineers, and Online Marketing Executive Jobs, Jobs in Colleges and Universities like Assistant Professor, Lecturer, Associate Professor, Researches, Computer Operator, Business Analyst and more are across India. Jobskar provides you the latest and all important jobs and also alerts the jobs directly by subscribing to our website E-mail alerts as well as Telegram Channel.
Candidates can get their latest and new active Design Instructor jobs through Jobskar. We acts as a pathway to list out the recent Design Instructor Jobs for all Design Instructor vacancies in various states such as Andhra Pradesh, Arunachal Pradesh, Assam, Bihar, Chhattisgarh, Gujarat, Goa, Haryana, Himachal Pradesh, Jharkhand, Jammu & Kashmir, Kerala, Karnataka, Ladakh, Madhya Pradesh, Maharashtra, Manipur, Meghalaya, Nagaland, Odisha, Punjab, Rajasthan, Sikkim, Telangana, Tamil Nadu, Tripura, Uttar Pradesh, Uttarakhand, Pondicherry and West Bengal. Job seekers can apply for their desired Design Instructor Jobs 2023 at Jobskar by clicking on the apply job button of any position to apply for the job. Before Appling any job candidates can check the eligibility criteria required by the specified organization.
To get immediate alerts about all the Latest Design Instructor Jobs 2023 and upcoming Design Instructor recruitments 2023 in the near future, you can subscribe to our Jobskar Free Jobs E-mail alerts service to get latest updates alerts directly to your Email as well as Jobskar.com Telegram Channel. Surely you can get instant alerts related to upcoming Design Instructor Jobs 2023. Candidates who are interested in applying for Design Instructor Jobs in different sectors such as SSC, UPSC, PSU, State PSC, Defence, Railway, Bank and etc can check this page regularly. Grow with us @ Jobskar.com. The future depends on what you do today. Your expectation is our reality. Our support is for Your Success. Good Luck!!!


text:
As we experience more of the unpleasant realities of the Affordable Care Act, Americans are questioning, finally, the forthrightness and honesty of their president in his selling of this law. As millions of individual health insurance policies are cancelled, it is transparent that the president distorted the truth when he told Americans, "if you like your plan you can keep it." But misrepresentation goes beyond how a particular feature of the law was sold. It also applies to the selling of what this whole law was supposed to be about.Read more ›
Archive for November 30th, 2013
The dishonest selling of Obamacare
by Star Parker / on November 30, 2013 at 12:16 am /
Subscribe by Email
Sign up to receive the daily American Clarion article digest, with links to articles.
Recent American Clarion Articles
- The Final American Clarion Article
After 12 and a half years, American Clarion and its parent company/website Dakota Voice are coming to an end. No more articles will be published here after this one, and in all likelihood, the website will be completely shut down when the current web hosting subscription expires in early
- Murder Incorporated: Taking Stock of the Culture of Death
There is an untold side of the tragic murder of Richard Wilbur Collins III by Sean Christopher Urbanski. In 2012 Richard graduated from Annapolis Area Christian School where he was taught to view all of life through the lens of God's Holy Word. He was taught that God created the Universe and
- SOS: Speaking of Seniors - Is This Medicare Advantage Fraud?
On May 25, 2017, I met at my office with a couple from Merrillville, Indiana. The wife's medical bill problems were routine and simple for me to resolve. But, the husband's medical bill issues were something that I had never seen in my over 14 years of helping seniors with Medicare related
- Keeping Memorial Day Memorable
What if I asked you, "Do you feel patriotic paying taxes to fund the central government's nationalization of the banks, the insurance industry, the automobile industry, the health care industry, and now local police forces or the use of the American military for unconstitutional and immoral,
- We All Just Need To Co-Exist – You First!
After the terror attack in Britain, Katy Perry pipes up in her ignorance and stated after the attack, "No barriers, no borders. We all need to co-exist." Katy wants the world to co-exist. I say, "You first, Katy!" Ironically, in a display of hypocrisy, Katy Perry has a gated entrance to her
- Ariana Grande and Salman Abedi: Both Deeply Deceived
It goes without saying that the loss of the young lives in Manchester England is a tragedy of the highest order. Even though they were chasing a pop-culture pipe dream they were subject to the kind of treatment that no one should ever have to
- By Whose Authority are Public Colleges 'Creating an Engaged and Inclusive Society'?
By whose authority? That is one of those critical questions that seems to never be asked in our day. It not only needs to be asked, I want to show you that is our duty and obligation as Christians to be asking this question rooted in a Christian world
Recent Archives
Monthly Archives
Popular Topics
2012 2014 2016 abortion America Christian Heritage Christianity conservatism Constitution crime culture defense Donald Trump economy education election ethnic issues First Amendment freedom free market GOP government health care history homosexuality illegal immigration Islam legislature liberalism marriage Marxism media bias morality Obama ObamaCare Rapid City religious freedom Republicans RINOs Second Amendment socialism South Dakota spending taxes terrorism(all tags)
Recent Comments
- OPUS: You too Gina.…
- WXRGina: :-) May God bless you, Opus.…
- OPUS: Thank you Gina for those kind words. I have seen the goodness in you, in your different articles. I wish……
- WXRGina: Opus, you're an interesting person. You're dedicated. I'm just thankful to God, period.…
- OPUS: Hi Gina good to see you. Have you been enjoying your summer so far?…
- WXRGina: Hi, Opus. :-)…
- Bob Ellis: Thank you! God bless your efforts to be a "fisher of men."…
- IgnorantFishermen: Bob my dear brother, thanks so much for your efforts these past years for none of it was ever……
- Bob Ellis: Thank you. And thanks for your support and encouragement, these years.…
- A. Castellitto: Godspeed Bob! You are an inspiration!…


text:
Did you know that fashion and comfort can be combined? This fleece crop sweatshirt is here to prove the point. The soft fabric feels extra soft to the touch, and the trendy cut with a ribbed neckline and raw hem comes right out of fashion magazines while still keeping it casual.
• 52% airlume combed and ring-spun cotton, 48% poly fleece
• Cropped body with a raw hem
• Ribbed crew neckline and cuffs
• Dropped shoulder
• Side-seamed


text: Devotional Light Church / Apostle Emmanuel A Adjei · TITHE AND OFFERINGS IN CHURCH SERVICE (Apostle Emmanuel A. Adjei) Share Share on Facebook Share on Twitter Share on Google Share on Pinterest 0 comments There are no comments yet. Be the first one to post a comment on this article! Leave a comment Name Email Message Please note, comments must be approved before they are published


text:
Hank UPF 30 Sun Shirt - Azure Blue
Product Description:
Short-Sleeve UV Protection Moisture Wicking Sun Shirt
Spending a day in the sun? Soak up the fun while blocking harmful UV rays with the UPF 30+ protection of a stylish short-sleeve sun shirt. Thin, quick-dry 100% microfibre polyester lets you dive in and out of the water in total comfort. The pill and snag-resistant weave stays sleek and smooth, with our classic wave logo on the front, and a unique Surfside Supply Co. graphic on the back. Great as an under-layer; perfect for following wherever the season leads you.
Product Details:
- Color: Azure Blue
- Soft Microfiber Polyester
- UPF 30+ Protection
- Quick-Dry Fabric
- Materials: 100% Polyester
Fabric Care:
- Machine Wash Cold With Like Colors
- Tumble Dry Low Heat
Sizing Info:
- Fits True to Size
We offer free ground shipping via UPS on all domestic orders (USA only) placed on our website, that are valued at $75.00 or more.
We understand that receiving your items quickly is important, so we make every effort to process and ship your order within one business day of it being received. When your order ships you can expect it to arrive within 2-8 business days.
Orders placed before 2:00 PM Eastern are typically shipped the same day (Monday-Friday) with the exception of holidays, closures due to inclement weather, or during times of high volume.
If you are not 100% satisfied with your purchase you can return your order for a full refund, or exchange for another size/item up to 60 days from the date of delivery. See rules and exemptions below.
We believe that in order to have the best possible online shopping experience, our USA customers should not have to pay for any return or exchange shipping costs. Customers do not need pre-pack their returning items, nor do they need to print out a return shipping label.
If for any reason you are not happy with your purchase please click here to start the return process.
Rules & Exemptions:
- Final sale merchandise cannot be returned.
- Shipping costs (if applicable) are non-refundable.
- All merchandise must be received by our warehouse within 60 days of delivery.
- Gift Cards are final sale and cannot be returned nor refunded.
- Damaged or visibly worn merchandise is ineligible for a refund/exchange and merchandise will be shipped back to the customer.
Please carefully review your order prior to purchase. If you have any questions or concerns please contact us via email at firstname.lastname@example.com
We typically respond to all emails within 24hrs and are here to help Monday - Friday 9:00am to 5:00pm Eastern (closed bank holidays).


text:
8 Passengers
7 Suitcase
Cancun Airport
8 max.
Mayambe Private Village
Did you know that the most important part of traveling is choosing the right transportation? We offer a safe and reliable Cancun Airport Shuttle to Mayambe Private Village at the best price. With us, it's easy to get to Mayambe Private Village, because we have a professional team of drivers who will take care of you. Book now and save time and money with AHS.
If you are looking for the best way to get from Cancun Airport to Mayambe Private Village, you are in the right place. With us, you can leave behind your transportation worries and avoid the hassle of driving after a long trip with low rates from $45.00.
When you book your private transportation service from Cancun airport to Mayambe Private Village you will have the peace of mind of receiving a professional service, which will allow you to travel comfortably, safely, and in the shortest time possible.
The Cancun Airport Transportation to Mayambe Private Village is available 24 hours a day with previous reservation, besides, all our services include flight monitoring, so you will not have to worry if your flight is delayed or advanced, your service will be available for you.
An efficient Taxi shuttle service from the Cancun Airport for up to 3 passengers with drinks included!.View Rates
Direct Cancun Airport Transportation in spacious vans for up to 8 passengers.View Rates
Exclusive transportation service to and from Cancun International Airport aboard luxury vehicles for up to 5 passengers.View Rates
Ideal service for groups, with comfortable vehicles for up to 15 passengers.View Rates
We would be more than happy to help you. Our call center is at your service.+1 (305) 529 3806
Sam W.
I liked the service. It was fast and cost-effective.
Total Score 5/5 (643 Reviews)
|Shuttle departs from:
|Cancun International Airport (CUN)
|Shuttle Destination:
|Mayambe Private Village
|From $45.00
|30 min approx
|21 km (13 mi)
|24 Hours, under booking.
|Services Available:
|Private Transportation, Airport Taxi, Luxury Transfers, Groups Transportation
|Type of Service:
|Transportation provided by:
Mayambe Private Village is located in Uxmal, and travel time for the transportation service from Cancun to Mayambe Private Village is approximately 4 H 5 min, depending on weather and traffic conditions.
At Airport Hotel Shuttle we have more than 10 years of experience offering the best service of transportation at the best price, and we know that after a long trip, the best thing is to be able to reach your destination in a fast and safe way, and through our Taxi service from the Cancun airport to Mayambe Private Village you will be able to do it at the lowest price. By hiring our Cancun Airport Transportation to Mayambe Private Village service you will not have to worry about sharing your vehicle with other passengers, making multiple stops to Uxmal or paying high fares as in other companies.
With us, you will be able to book the best Cancun Airport Transfers to Mayambe Private Village from $45.00.


text:
Additional FAQ Entries on this Wiki
Translations of this Document
Platform-specific questions
Windows users should also read the platform FAQ for Windows. There are FAQs for other platforms too.
General Questions
What is PostgreSQL? How is it pronounced? What is Postgres?
PostgreSQL is pronounced Post-Gres-Q-L. (For those curious about how to say "PostgreSQL", an audio file is available.)
PostgreSQL is an object-relational database system that has the features of traditional proprietary database systems with enhancements to be found in next-generation DBMS systems. PostgreSQL is free and the complete source code is available.
PostgreSQL development is performed by a team of mostly volunteer developers spread throughout the world and communicating via the Internet. It is a community project and is not controlled by any company. To get involved, see the Developer FAQ.
Postgres is a widely-used nickname for PostgreSQL. It was the original name of the project at Berkeley and is strongly preferred over other nicknames. If you find 'PostgreSQL' hard to pronounce, call it 'Postgres' instead.
Who controls PostgreSQL?
If you are looking for a PostgreSQL gatekeeper, central committee, or controlling company, give up --- there isn't one. We do have a core committee and CVS committers, but these groups are more for administrative purposes than control. The project is directed by the community of developers and users, which anyone can join. All you need to do is subscribe to the mailing lists and participate in the discussions. (See the Developer's FAQ for information on how to get involved in PostgreSQL development.)
Who is the PostgreSQL Global Development Group?
The "PGDG" is an international, unincorporated association of individuals and companies who have contributed to the PostgreSQL project. The PostgreSQL Core Team generally act as spokespeople for the PGDG.
Who is the PostgreSQL Core Team?
A committee of five to seven (currently six) senior contributors to PostgreSQL who do the following for the project: (a) set release dates, (b) handle confidential matters for the project, (c) act as spokespeople for the PGDG when required, and (d) arbitrate community decisions which are not settled by consensus. The current Core Team is listed on top of the contributors page
What about the various PostgreSQL foundations?
While the PostgreSQL project utilizes non-profit corporations in the USA, Europe, Brazil and Japan for fundraising and project coordination, these entities do not own the PostgreSQL code.
What is the license of PostgreSQL?
PostgreSQL is distributed under a license similar to BSD and MIT. Basically, it allows users to do anything they want with the code, including reselling binaries without the source code. The only restriction is that you not hold us legally liable for problems with the software. There is also the requirement that this copyright appear in all copies of the software. Here is the license we use:
PostgreSQL Database Management System (formerly known as Postgres, then as Postgres95) Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group Portions Copyright (c) 1994, The Regents of the University of California Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
What platforms does PostgreSQL support?
In general, any modern Unix-compatible platform should be able to run PostgreSQL. The platforms that have received recent explicit testing can be seen in the Build farm. The documentation contains more details about supported platforms at http://www.postgresql.org/docs/current/static/supported-platforms.html.
PostgreSQL also runs natively on Microsoft Windows NT-based operating systems like Win2000 SP4, WinXP, and Win2003. A prepackaged installer is available at http://www.postgresql.org/download/windows. MSDOS-based versions of Windows (Win95, Win98, WinMe) can run PostgreSQL using Cygwin.
Where can I get PostgreSQL?
There are binary distributions for various operating systems and platforms; see our download area.
The source code can be obtained via web browser or through ftp.
What is the most recent release?
The latest release of PostgreSQL is shown on the front page of our website.
We typically have a major release every year, with minor releases every few months. Minor releases are usually made at the same time for all supported major-release branches. For more about major versus minor releases, see http://www.postgresql.org/support/versioning.
Where can I get support?
The PostgreSQL community provides assistance to many of its users via email. The main web site to subscribe to the email lists is http://www.postgresql.org/community/lists/. The general or bugs lists are a good place to start. For best results, consider reading the guide to reporting problems before you post to make sure you include enough information for people to help you.
The major IRC channel is #postgresql on Freenode (irc.freenode.net). A Spanish one also exists on the same network, (#postgresql-es), a French one, (#postgresqlfr), and a Brazilian one, (#postgresql-br). There is also a PostgreSQL channel on EFNet.
A list of support companies is available at http://www.postgresql.org/support/professional_support.
How do I submit a bug report?
Visit the PostgreSQL bug form at http://www.postgresql.org/support/submitbug to submit your bug report to the pgsql-bugs mailing list. Also check out our ftp site ftp://ftp.postgresql.org/pub/ to see if there is a more recent PostgreSQL version.
For a prompt and helpful response, it is important for you to read the guide to reporting problems to make sure that you include the information required to fully understand and act on your report.
Bugs submitted using the bug form or posted to any PostgreSQL mailing list typically generates one of the following replies:
- It is not a bug, and why
- It is a known bug and is already on the TODO list
- The bug has been fixed in the current release
- The bug has been fixed but is not packaged yet in an official release
- A request is made for more detailed information:
- Operating system
- PostgreSQL version
- Reproducible test case
- Debugging information
- Debugger backtrace output
- The bug is new. The following might happen:
- A patch is created and will be included in the next major or minor release
- The bug cannot be fixed immediately and is added to the TODO list
How do I find out about known bugs or missing features?
PostgreSQL supports an extended subset of SQL:2008. See our TODO list for known bugs, missing features, and future plans.
A feature request usually results in one of the following replies:
- The feature is already on the TODO list
- The feature is not desired because:
- It duplicates existing functionality that already follows the SQL standard
- The feature would increase code complexity but add little benefit
- The feature would be insecure or unreliable
- The new feature is added to the TODO list
PostgreSQL does not use a bug tracking system because we find it more efficient to respond directly to email and keep the TODO list up-to-date. In practice, bugs don't last very long in the software, and bugs that affect a large number of users are fixed rapidly. The only place to find all changes, improvements, and fixes in a PostgreSQL release is to read the CVS log messages. Even the release notes do not list every change made to the software.
A bug I'm encountering is fixed in a newer minor release of PostgreSQL, but I don't want to upgrade. Can I get a patch for just this issue?
No. Nobody will make a custom patch for you so you can (say) extract a fix from 8.4.3 and apply it to 8.4.1 . That's because there should never be any need to do that.
PostgreSQL has a strict policy that only bug fixes are back-patched into point releases, as per the version policy. It is safe to upgrade from 8.4.1 to 8.4.3, for example. Binary compatibility will be maintained, no dump and reload is required, nothing will break, but bugs that might cause problems have been fixed. Even if you are not yet encountering a particular bug, you might later, and it is wise to upgrade promptly. You just have to install the update and re-start the database server, nothing more.
Upgrading from 8.3 to 8.4, or 8.4 to 9.0, is a major upgrade that does not come with the same guarantees. However, if a bug is discovered in 9.0 then it will generally be fixed in all maintained older versions like 8.4 and 8.3 if it is safe and practical to do so.
This means that if you're running 8.1.0, upgrading to 8.1.21 is strongly recommended and very safe. On the other hand, upgrading to the next major release, 8.2.x, may require changes to your app, and will certainly require a dump and reload.
If you want to be careful about all upgrades, you should read the release notes for each point release between your current one and the latest minor version of the same major release carefully. If you're exceptionally paranoid about upgrades, you can fetch the source code to each set of point release changes from PostgreSQL's git repository and examine it.
It is strongly recommended that you always upgrade to the latest minor release. Avoid trying to extract and apply individual fixes from point releases; by doing so you're bypassing all the QA done by the PostgreSQL team when they prepare a release, and are creating your own custom version that nobody else has ever used. It's a lot safer to just update to the latest tested, safe release. Patching your own custom, non-standard build will also take more time/effort, and will require the same amount of downtime as a normal upgrade.
I have a program that says it wants PostgreSQL x.y.1. Can I use PostgreSQL x.y.2 instead?
Any program that works with a particular version, like 8.4.1, should work with any other minor version in the same major version. That means that if a program says it wants (eg) 8.4.1, you can and should install the latest in the 8.4 series instead.
See the previous question for more details.
What documentation is available?
PostgreSQL includes extensive documentation, including a large manual, manual pages, and some test examples. See the /doc directory. You can also browse the manuals online at http://www.postgresql.org/docs.
There are a number of PostgreSQL books available for purchase; two of them are also available online. A list of books can be found at http://www.postgresql.org/docs/books/. One of the most popular ones is the one by Korry & Susan Douglas.
There is also a collection of PostgreSQL technical articles on the wiki.
The command line client program psql has some \d commands to show information about types, operators, functions, aggregates, etc. - use \? to display the available commands.
How can I learn SQL?
First, consider the PostgreSQL-specific books mentioned above. Many of our users also like The Practical SQL Handbook, Bowman, Judith S., et al., Addison-Wesley. Others like The Complete Reference SQL, Groff et al., McGraw-Hill.
Many people consider the PostgreSQL documentation to be an excellent guide for learning SQL its self, as well as for PostgreSQL's implementation of it. For best results use PostgreSQL alongside another full-featured SQL database as you learn, so you get used to SQL without becoming reliant on PostgreSQL-specific features. The PostgreSQL documentation generally mentions when features are PostgreSQL extensions of the standard.
There are also many nice tutorials available online:
- http://www.intermedia.net/support/sql/sqltut.shtm
- http://sqlcourse.com
- http://www.w3schools.com/sql/default.asp
- http://mysite.verizon.net/Graeme_Birchall/id1.html
- http://sqlzoo.net
How do I submit a patch or join the development team?
See the Developer's FAQ.
How does PostgreSQL compare to other DBMSs?
There are several ways of measuring software: features, performance, reliability, support, and price.
PostgreSQL has most features present in large proprietary DBMSs, like transactions, subselects, triggers, views, foreign key referential integrity, and sophisticated locking. We have some features they do not have, like user-defined types, inheritance, rules, and multi-version concurrency control to reduce lock contention.
PostgreSQL's performance is comparable to other proprietary and open source databases. It is faster for some things, slower for others. Our performance is usually +/-10% compared to other databases.
We realize that a DBMS must be reliable, or it is worthless. We strive to release well-tested, stable code that has a minimum of bugs. Each release has at least one month of beta testing, and our release history shows that we can provide stable, solid releases that are ready for production use. We believe we compare favorably to other database software in this area.
Our mailing lists provide contact with a large group of developers and users to help resolve any problems encountered. While we cannot guarantee a fix, proprietary DBMSs do not always supply a fix either. Direct access to developers, the user community, manuals, and the source code often make PostgreSQL support superior to other DBMSs. There is commercial per-incident support available for those who need it. (See section 1.7).
We are free for all use, both proprietary and open source. You can add our code to your product with no limitations, except those outlined in our BSD-style license stated above.
Can PostgreSQL be embedded?
PostgreSQL is designed as a client/server architecture, which requires separate processes for each client and server, and various helper processes. Many embedded architectures can support such requirements. However, if your embedded architecture requires the database server to run inside the application process, you cannot use Postgres and should select a lighter-weight database solution.
Popular embeddable options include SQLite and Firebird SQL.
How do I unsubscribe from the PostgreSQL email lists? How do I avoid receiving duplicate emails?
The PostgreSQL Majordomo page allows subscribing or unsubscribing from any of the PostgreSQL email lists. (You might need to have your Majordomo password emailed to you to log in.)
All PostgreSQL email lists are configured so a group reply goes to the email list and the original email author. This is done so users receive the quickest possible email replies. If you would prefer not to receive duplicate email from the list in cases where you already receive an email directly, check eliminatecc from the Majordomo Change Settings page. You can also prevent yourself from receiving copies of emails you post to the lists by unchecking selfcopy.
User Client Questions
What interfaces are available for PostgreSQL?
The PostgreSQL install includes only the C and embedded C interfaces. All other interfaces are independent projects that are downloaded separately; being separate allows them to have their own release schedule and development teams.
Some programming languages like PHP include an interface to PostgreSQL. Interfaces for languages like Perl, TCL, Python, and many others are available at http://pgfoundry.org.
What tools are available for using PostgreSQL with Web pages?
A nice introduction to Database-backed Web pages can be seen at: http://www.webreview.com
For Web integration, PHP (http://www.php.net) is an excellent interface.
For complex cases, many use the Perl and DBD::Pg with CGI.pm or mod_perl.
Does PostgreSQL have a graphical user interface?
There are a large number of GUI Tools that are available for PostgreSQL from both proprietary and open source developers. A detailed list can be found in the Community Guide to PostgreSQL GUI Tools.
Administrative Questions
How do I install PostgreSQL somewhere other than /usr/local/pgsql?
Specify the --prefix option when running configure.
I'm installing PostgreSQL and don't know the password for the postgres user
Dave Page wrote a blog post explaining what the different passwords are used for, and how to overcome common problems such as resetting them.
How do I control connections from other hosts?
By default, PostgreSQL only allows connections from the local machine using Unix domain sockets or TCP/IP connections. Other machines will not be able to connect unless you modify listen_addresses in the postgresql.conf file, enable host-based authentication by modifying the $PGDATA/pg_hba.conf file, and restart the database server.
How do I tune the database engine for better performance?
There are three major areas for potential performance improvement:
Query Changes
This involves modifying queries to obtain better performance:
- Creation of indexes, including expression and partial indexes
- Use of COPY instead of multiple INSERTs
- Grouping of multiple statements into a single transaction to reduce commit overhead
- Use of CLUSTER when retrieving many rows from an index
- Use of LIMIT for returning a subset of a query's output
- Use of Prepared queries
- Use of ANALYZE to maintain accurate optimizer statistics
- Regular use of VACUUM or pg_autovacuum
- Dropping of indexes during large data changes
Server Configuration
A number of postgresql.conf settings affect performance. For more details, see Administration Guide/Server Run-time Environment/Run-time Configuration.
Hardware Selection
The effect of hardware on performance is detailed in http://www.powerpostgresql.com/PerfList/ and http://momjian.us/main/writings/pgsql/hw_performance/index.html.
What debugging features are available?
There are many log_* server configuration variables at http://www.postgresql.org/docs/current/interactive/runtime-config-logging.html that enable printing of query and process statistics which can be very useful for debugging and performance measurements.
Why do I get "Sorry, too many clients" when trying to connect?
You have reached the default limit of 100 database sessions. You need to increase the server's limit on how many concurrent backend processes it can start by changing the max_connections value in postgresql.conf and restarting the server.
What is the upgrade process for PostgreSQL?
See http://www.postgresql.org/support/versioning for a general discussion about upgrading, and http://www.postgresql.org/docs/current/static/install-upgrading.html for specific instructions.
Will PostgreSQL handle recent daylight saving time changes in various countries?
PostgreSQL releases 8.0 and up depend on the widely-used tzdata database (also called the zoneinfo database or the Olson timezone database) for daylight savings information. To deal with a DST law change that affects you, install a new tzdata file set and restart the server.
All PostgreSQL update releases include the latest available tzdata files, so keeping up-to-date on minor releases for your major version is usually sufficient for this.
On platforms that receive regular software updates including new tzdata files, it may be more convenient to rely on the system's copy of the tzdata files. This is possible as a compile-time option. Most Linux distributions choose this approach for their pre-built versions of PostgreSQL.
PostgreSQL releases before 8.0 always rely on the operating system's timezone information.
What computer hardware should I use?
Because PC hardware is mostly compatible, people tend to believe that all PC hardware is of equal quality. It is not. ECC RAM, SCSI, and quality motherboards are more reliable and have better performance than less expensive hardware. PostgreSQL will run on almost any hardware, but if reliability and performance are important it is wise to research your hardware options thoroughly.
Database servers, unlike many other applications, are usually I/O and memory constrained, so it is wise to focus on the I/O subsystem first, then memory capacity, and lastly consider CPU issues. For example, a disk controller with a battery-backed cache is often the cheapest and easiest way to improve database performance. Our email lists can be used to discuss hardware options and tradeoffs.
How does PostgreSQL use CPU resources?
The PostgreSQL server is process-based (not threaded), and uses one operating system process per database session. A single database session (connection) cannot utilize more than one CPU. Of course, multiple sessions are automatically spread across all available CPUs by your operating system. Client applications can easily use threads and create multiple database connections from each thread.
A single complex and CPU-intensive query is unable to use more than one CPU to do the processing for the query. The OS may still be able to use others for disk I/O etc, but you won't see much benefit from more than one spare core.
Why does PostgreSQL have so many processes, even when idle?
As noted in the answer above, PostgreSQL is process based, so it starts one
postgres (or
postgres.exe on Windows) instance per connection. The postmaster (which accepts connections and starts new postgres instances for them) is always running. In addition, PostgreSQL generally has one or more "helper" processes like the stats collector, background writer, autovacuum daemon, walsender, etc, all of which show up as "postgres" instances in most system monitoring tools.
Despite the number of processes, they actually use very little in the way of real resources. See the next answer.
Why does PostgreSQL use so much memory?
Despite appearances, this is absolutely normal, and there's actually nowhere near as much memory being used as tools like
top or the Windows process monitor say PostgreSQL is using.
Tools like
top and the Windows process monitor may show many
postgres instances (see above), each of which appears to use a huge amount of memory. Often, when added up, the amount the postgres instances use is many times the amount of memory actually installed in the computer!
This is a consequence of how these tools report memory use. They generally don't understand shared memory very well, and show it as if it was memory used individually and exclusively by each postgres instance. PostgreSQL uses a big chunk of shared memory to communicate between its backends and cache data. Because these tools count that shared memory block once per
postgres instance instead of counting it once for all
postgres instances, they massively over-estimate how much memory PostgreSQL is using.
Operational Questions
How do I SELECT only the first few rows of a query? A random row?
To retrieve only a few rows, if you know at the number of rows needed at the time of the SELECT use LIMIT . If an index matches the ORDER BY it is possible the entire query does not have to be executed. If you don't know the number of rows at SELECT time, use a cursor and FETCH.
To SELECT a random row, use:
SELECT col FROM tab ORDER BY random() LIMIT 1;
See also this blog entry by Andrew Gierth that has more information on this topic.
How do I find out what tables, indexes, databases, and users are defined? How do I see the queries used by psql to display them?
Use the \dt command to see tables in psql. For a complete list of commands inside psql you can use \?. Alternatively you can read the source code for psql in file pgsql/src/bin/psql/describe.c, it contains SQL commands that generate the output for psql's backslash commands. You can also start psql with the -E option so it will print out the queries it uses to execute the commands you give. PostgreSQL also provides an SQL compliant INFORMATION SCHEMA interface you can query to get information about the database.
There are also system tables beginning with pg_ that describe these too.
Use psql -l will list all databases.
Also try the file pgsql/src/tutorial/syscat.source. It illustrates many of the SELECTs needed to get information from the database system tables.
How do you change a column's data type?
Changing the data type of a column can be done easily in 8.0 and later with ALTER TABLE ALTER COLUMN TYPE.
In earlier releases, do this:
BEGIN; ALTER TABLE tab ADD COLUMN new_col new_data_type; UPDATE tab SET new_col = CAST(old_col AS new_data_type); ALTER TABLE tab DROP COLUMN old_col; COMMIT;
You might then want to do VACUUM FULL tab to reclaim the disk space used by the expired rows.
What is the maximum size for a row, a table, and a database?
These are the limits:
Maximum size for a database? unlimited (32 TB databases exist) Maximum size for a table? 32 TB Maximum size for a row? 400 GB Maximum size for a field? 1 GB Maximum number of rows in a table? unlimited Maximum number of columns in a table? 250-1600 depending on column types Maximum number of indexes on a table? unlimited
Of course, these are not actually unlimited, but limited to available disk space and memory/swap space. Performance may suffer when these values get unusually large.
The maximum table size of 32 TB does not require large file support from the operating system. Large tables are stored as multiple 1 GB files so file system size limits are not important.
The maximum table size, row size, and maximum number of columns can be quadrupled by increasing the default block size to 32k. The maximum table size can also be increased using table partitioning.
One limitation is that indexes can not be created on columns longer than about 2,000 characters. Fortunately, such indexes are rarely needed. Uniqueness is best guaranteed by a function index of an MD5 hash of the long column, and full text indexing allows for searching of words within the column.
How much database disk space is required to store data from a typical text file?
A PostgreSQL database may require up to five times the disk space to store data from a text file.
As an example, consider a file of 100,000 lines with an integer and text description on each line. Suppose the text string averages twenty bytes in length. The flat file would be 2.8 MB. The size of the PostgreSQL database file containing this data can be estimated as 5.2 MB:
24 bytes: each row header (approximate) 24 bytes: one int field and one text field + 4 bytes: pointer on page to tuple ---------------------------------------- 52 bytes per row
The data page size in PostgreSQL is 8192 bytes (8 KB), so:
8192 bytes per page ------------------- = 158 rows per database page (rounded down) 52 bytes per row
100000 data rows ------------------ = 633 database pages (rounded up) 158 rows per page
633 database pages * 8192 bytes per page = 5,185,536 bytes (5.2 MB)
Indexes do not require as much overhead, but do contain the data that is being indexed, so they can be large also.
NULLs are stored as bitmaps, so they use very little space.
Note that long values may be compressed transparently.
See also this presentation on the topic: File:How Long Is a String.pdf.
Why are my queries slow? Why don't they use my indexes?
Indexes are not used by every query. Indexes are used only if the table is larger than a minimum size, and the query selects only a small percentage of the rows in the table. This is because the random disk access caused by an index scan can be slower than a straight read through the table, or sequential scan.
To determine if an index should be used, PostgreSQL must have statistics about the table. These statistics are collected using VACUUM ANALYZE, or simply ANALYZE. Using statistics, the optimizer knows how many rows are in the table, and can better determine if indexes should be used. Statistics are also valuable in determining optimal join order and join methods. Statistics collection should be performed periodically as the contents of the table change.
Indexes are normally not used for ORDER BY or to perform joins. A sequential scan followed by an explicit sort is usually faster than an index scan of a large table. However, LIMIT combined with ORDER BY often will use an index because only a small portion of the table is returned.
If you believe the optimizer is incorrect in choosing a sequential scan, use SET enable_seqscan TO 'off' and run query again to see if an index scan is indeed faster.
When using wild-card operators such as LIKE or ~, indexes can only be used in certain circumstances:
- The beginning of the search string must be anchored to the start of the string, i.e.
- LIKE patterns must not start with % or _.
- ~ (regular expression) patterns must start with ^.
- The search string can not start with a character class, e.g. [a-e].
- Case-insensitive searches such as ILIKE and ~* do not utilize indexes. Instead, use expression indexes, which are described in section 4.8.
- C locale must be used during initdb because sorting in a non-C locale often doesn't match the behavior of LIKE. You can create a special text_pattern_ops index that will work in such cases, but note it is only helpful for LIKE indexing.
It is also possible to use full text indexing for word searches.
The SlowQueryQuestions article contains some more tips and guidance.
How do I see how the query optimizer is evaluating my query?
This is done with the EXPLAIN command; see Using EXPLAIN.
How do I change the sort ordering of textual data?
PostgreSQL sorts textual data according to the ordering that is defined by the current locale, which is selected during initdb. (In 8.4 and up it will be possible to select a different locale when creating a new database.) If you don't like the ordering then you need to use a different locale. In particular, most locales other than "C" sort according to dictionary order, which largely ignores punctuation and spacing. If that's not what you want then you need "C" locale.
How do I perform regular expression searches and case-insensitive regular expression searches? How do I use an index for case-insensitive searches?
The ~ operator does regular expression matching, and ~* does case-insensitive regular expression matching. The case-insensitive variant of LIKE is called ILIKE.
Case-insensitive equality comparisons are normally expressed as:
SELECT * FROM tab WHERE lower(col) = 'abc';
This will not use a standard index on "col". However, if you create an expression index on "lower(col)", it will be used:
CREATE INDEX tabindex ON tab (lower(col));
If the above index is created as UNIQUE, then the column can store upper and lowercase characters, but it cannot contain identical values that differ only in case. To force a particular case to be stored in the column, use a CHECK constraint or a trigger.
In PostgreSQL 8.4 and later, you can also use the contributed CITEXT data type, which internally implements the "lower()" calls, so that you can effectively treat it as a fully case-insensitive data type. CITEXT is also available for 8.3, and an earlier version that treats only ASCII characters case-insensitively on 8.2 and earlier is available on pgFoundry.
In a query, how do I detect if a field is NULL? How do I concatenate possible NULLs? How can I sort on whether a field is NULL or not?
You can test the value with IS NULL or IS NOT NULL, like this:
SELECT * FROM tab WHERE col IS NULL;
Concatenating a NULL with something else produces another NULL. If that's not what you want, you can replace the NULL(s) using COALESCE(), like this:
SELECT COALESCE(col1, '') || COALESCE(col2, '') FROM tab;
To sort by the NULL status, use an IS NULL or IS NOT NULL test in your ORDER BY clause. Things that are true will sort higher than things that are false, so the following will put NULL entries at the front of the output:
SELECT * FROM tab ORDER BY (col IS NOT NULL), col;
In PostgreSQL 8.3 and up, you can also control sort ordering of NULLs using the recently-standardized NULLS FIRST/NULLS LAST modifiers, like this:
SELECT * FROM tab ORDER BY col NULLS FIRST;
What is the difference between the various character types?
|Internal Name
|size specifies maximum length, no padding
|blank-padded to the specified fixed length
|no specific upper limit on length
|variable-length byte array (null-byte safe)
|"char" (with the quotes)
|one byte
You will see the internal name when examining system catalogs and in some error messages.
The first four types above are "varlena" types (i.e., the field length is explicitly stored on disk, followed by the data). Thus the actual space used is slightly greater than the expected size. However, long values are also subject to compression, so the space on disk might also be less than expected.
VARCHAR(n) is best when storing variable-length strings if a specific upper limit on the string length is required by the application. TEXT is for strings of "unlimited" length (though all fields in PostgreSQL are subject to a maximum value length of one gigabyte).
CHAR(n) is for storing strings that are all the same length. CHAR(n) pads with blanks to the specified length, while VARCHAR(n) only stores the characters supplied. BYTEA is for storing binary data, particularly values that include zero bytes. All these types have similar performance characteristics, except that the blank-padding involved in CHAR(n) requires additional storage and some extra runtime.
The "char" type (the quotes are required to distinguish it from CHAR(n)) is a specialized datatype that can store exactly one byte. It is found in the system catalogs but its use in user tables is generally discouraged.
How do I create a serial/auto-incrementing field?
PostgreSQL supports a SERIAL data type. Actually, this isn't quite a real type. It's a shorthand for creating an integer column that is fed from a sequence.
For example, this:
CREATE TABLE person ( id SERIAL, name TEXT );
is automatically translated into this:
CREATE SEQUENCE person_id_seq; CREATE TABLE person ( id INTEGER NOT NULL DEFAULT nextval('person_id_seq'), name TEXT );
The automatically created sequence is named table_serialcolumn_seq, where table and serialcolumn are the names of the table and SERIAL column, respectively. See the CREATE SEQUENCE manual page for more information about sequences.
There is also BIGSERIAL, which is like SERIAL except that the resulting column is of type BIGINT instead of INTEGER. Use this type if you think that you might need more than 2 billion serial values over the lifespan of the table.
How do I get the value of a SERIAL insert?
The simplest way is to retrieve the assigned SERIAL value with RETURNING. Using the example table in the previous question, it would look like this:
INSERT INTO person (name) VALUES ('Blaise Pascal') RETURNING id;
You can also call nextval() and use that value in the INSERT, or call currval() after the INSERT.
Doesn't currval() lead to a race condition with other users?
No. currval() returns the latest sequence value assigned by your session, independently of what is happening in other sessions.
Why are there gaps in the numbering of my sequence/SERIAL column? Why aren't my sequence numbers reused on transaction abort?
To improve concurrency, sequence values are given out to running transactions on-demand; the sequence object is not kept locked but is immediately available for another transaction to get another sequence value. This causes gaps in numbering from aborted transactions.
What is an OID?
If a table is created WITH OIDS, each row includes an OID column that is automatically filled in during INSERT. OIDs are sequentially assigned 4-byte integers. Initially they are unique across the entire installation. However, the OID counter wraps around at 4 billion, and after that OIDs may be duplicated.
It is possible to prevent duplication of OIDs within a single table by creating a unique index on the OID column (but note that the WITH OIDS clause doesn't by itself create such an index). The system checks the index to see if a newly generated OID is already present, and if so generates a new OID and repeats. This works well so long as no OID-containing table has more than a small fraction of 4 billion rows.
PostgreSQL uses OIDs for object identifiers in the system catalogs, where the size limit is unlikely to be a problem.
To uniquely number rows in user tables, it is best to use SERIAL rather than an OID column, or BIGSERIAL if the table is expected to have more than 2 billion entries over its lifespan.
What is a CTID?
CTIDs identify specific physical rows by their block and offset positions within a table. They are used by index entries to point to physical rows. A logical row's CTID changes when it is updated, so the CTID cannot be used as a long-term row identifier. But it is sometimes useful to identify a row within a transaction when no competing update is expected.
Why do I get the error "ERROR: Memory exhausted in AllocSetAlloc()"?
You probably have run out of virtual memory on your system, or your kernel has a low limit for certain resources. Try this before starting the server:
ulimit -d 262144 limit datasize 256m
Depending on your shell, only one of these may succeed, but it will set your process data segment limit much higher and perhaps allow the query to complete. This command applies to the current process, and all subprocesses created after the command is run. If you are having a problem with the SQL client because the backend is returning too much data, try it before starting the client.
How do I tell what PostgreSQL version I am running?
Run this query: SELECT version();
Is there a way to leave an audit trail of database operations?
There's nothing built-in, but it's not too difficult to build such facilities yourself.
Simple example right in the official docs: http://www.postgresql.org/docs/8.3/static/plpgsql-trigger.html#PLPGSQL-TRIGGER-AUDIT-EXAMPLE
Project targeting this feature: http://pgfoundry.org/projects/tablelog/
Background information and other sample implementations: http://it.toolbox.com/blogs/database-soup/simple-data-auditing-19014 http://www.go4expert.com/forums/showthread.php?t=7252 http://www.alberton.info/postgresql_table_audit.html
How do I create a column that will default to the current time?
Use CURRENT_TIMESTAMP:
CREATE TABLE test (x int, modtime TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
How do I perform an outer join?
PostgreSQL supports outer joins using the SQL standard syntax. Here are two examples:
SELECT * FROM t1 LEFT OUTER JOIN t2 ON (t1.col = t2.col);
SELECT * FROM t1 LEFT OUTER JOIN t2 USING (col);
These identical queries join t1.col to t2.col, and also return any unjoined rows in t1 (those with no match in t2). A RIGHT join would add unjoined rows of t2. A FULL join would return the matched rows plus all unjoined rows from t1 and t2. The word OUTER is optional and is assumed in LEFT, RIGHT, and FULL joins. Ordinary joins are called INNER joins.
How do I perform queries using multiple databases?
There is no way to query a database other than the current one. Because PostgreSQL loads database-specific system catalogs, it is uncertain how a cross-database query should even behave.
contrib/dblink allows cross-database queries using function calls. Of course, a client can also make simultaneous connections to different databases and merge the results on the client side.
How do I return multiple rows or columns from a function?
It is easy using set-returning functions, Return more than one row of data from PL/pgSQL functions.
Why do I get "relation with OID ##### does not exist" errors when accessing temporary tables in PL/PgSQL functions?
In PostgreSQL versions < 8.3, PL/PgSQL caches function scripts, and an unfortunate side effect is that if a PL/PgSQL function accesses a temporary table, and that table is later dropped and recreated, and the function called again, the function will fail because the cached function contents still point to the old temporary table. The solution is to use EXECUTE for temporary table access in PL/PgSQL. This will cause the query to be reparsed every time.
This problem does not occur in PostgreSQL 8.3 and later.
What replication solutions are available?
Though "replication" is a single term, there are several technologies for doing replication, with advantages and disadvantages for each. Our documentation contains a good introduction to this topic at http://www.postgresql.org/docs/8.3/static/high-availability.html and a grid listing replication software and features is at Replication, Clustering, and Connection Pooling
Master/slave replication allows a single master to receive read/write queries, while slaves can only accept read/SELECT queries. The most popular freely available master-slave PostgreSQL replication solution is Slony-I.
Multi-master replication allows read/write queries to be sent to multiple replicated computers. This capability also has a severe impact on performance due to the need to synchronize changes between servers. PGCluster is the most popular such solution freely available for PostgreSQL.
There are also proprietary and hardware-based replication solutions available supporting a variety of replication models.
PostgreSQL does not support clustering using shared storage on a SAN, SCSI backplane, iSCSI volume, or other shared media. Such "RAC-style" clustering isn't supported. Only replication-based clustering is currently supported.
See Replication, Clustering, and Connection Pooling information for details.
Shared-storage 'failover' is possible, but it is not safe to have more than one postmaster running and accessing the data store at the same time. Heartbeat and STONITH or some other hard-disconnect option are recommended.
Why are my table and column names not recognized in my query? Why is capitalization not preserved?
The most common cause of unrecognized names is the use of double-quotes around table or column names during table creation. When double-quotes are used, table and column names (called identifiers) are stored case-sensitive, meaning you must use double-quotes when referencing the names in a query. Some interfaces, like pgAdmin, automatically double-quote identifiers during table creation. So, for identifiers to be recognized, you must either:
- Avoid double-quoting identifiers when creating tables
- Use only lowercase characters in identifiers
- Double-quote identifiers when referencing them in queries
I lost the database password. What can I do to recover it?
You can't. However, you can reset it to something else. To do this, you
- edit pg_hba.conf to allow trust authorization temporarily
- Reload the config file (pg_ctl reload)
- Connect and issue ALTER ROLE / PASSWORD to set the new password
- edit pg_hba.conf again and restore the previous settings
- Reload the config file again
Does PostgreSQL have stored procedures?
PostgreSQL doesn't. However PostgreSQL have very powerful functions and user-defined functions capabilities that can do most things that other RDBMS stored routines (procedures and functions) can do and in many cases more.
These functions can be of different types and can be implemented in several programming languages. (Refer to documentation for more details. User-Defined Functions)
PostgreSQL functions can be invoked in many ways. If you want to invoke a function as you would call a stored procedure in other RDBMS (typically a function with side-effects but whose result you don't care for example because it returns void), one option would be to use PL/pgSQL Language for your procedure and the PERFORM command. Example:
PERFORM theNameOfTheFunction(arg1, arg2);
Note that invoking instead:
SELECT theNameOfTheFunction(arg1, arg2);
would produce a result even if the function returns void (this result would be one row containing a void value).
PERFORM could thus be used to discard this unuseful result.
The main limitations on Pg's stored functions - as compared to true stored procedures - are:
- inability to return multiple result sets
- no support for autonomous transactions (
ROLLBACKwithin a function)
- no support for the SQL-standard
CALLsyntax, though the ODBC and JDBC drivers will translate calls for you.
Why don't BEGIN, ROLLBACK and COMMIT work in stored procedures/functions?
PostgreSQL doesn't support autonomous transactions in its stored functions. Like all PostgreSQL queries, stored functions always run in a transaction and cannot operate outside a transaction.
If you need a stored procedure to manage transactions, you can look into the dblink interface or do the work from a client-side script instead. In some cases you can do what you need to using exception blocks in PL/PgSQL, because each BEGIN/EXCEPTION/END block creates a subtransaction.
Why is "SELECT count(*) FROM bigtable;" slow?
It can't be answered directly from an index. PostgreSQL has to check the visibility for each record, so it forces a sequential scan of the entire table. If you want, you can keep track of the number of rows yourself with triggers, but beware that this will slow down write access to the table.
You can get an estimation. The reltuples column in pg_class contains the information from the latest ANALYZE of the table. On a large table this is often accurate to within a few thousandths of a percent, which is accurate enough for many purposes.
An "exact" count is often not exact for very long, anyway; due to MVCC concurrency, the count will be accurate as of the moment the SELECT count(*) query (or, for stricter transaction isolation levels, its transaction) started, and may well be out-of-date by the time the query completes. In a transaction mix where the table is being modified, two count(*) executions which return at the same moment might have different values, if a modifying transaction committed between their start times.
For more information, see Slow Counting.
Why is my query much slower when run as a prepared query?
When PostgreSQL has the full query with all parameters known by planning time, it can use statistics in the table to find out if the values used in the query are very common or very uncommon in a column. This lets it change the way it fetches the data to be more efficient, as it knows to expect lots or very few results from a certain part of the query. For example, it might choose an sequential scan instead of doing an index scan if you search for 'active=y' and it knows that 99% of the records in the table have 'active=y', because in this case a sequential scan will be much faster.
In a prepared query, PostgreSQL doesn't have the value of all parameters when it's creating the plan. It has to try to pick a "safe" plan that should work fairly well no matter what value you supply as the parameter when you execute the prepared query. Unfortunately, this plan might not be very appropriate if the value you supply is vastly more common, or vastly less common, than is average for some randomly selected values in the table.
If you suspect this issue is affecting you, start by using the EXPLAIN command to compare the slow and fast queries. Look at the output of
EXPLAIN SELECT query... and compare it to the result of
PREPARE query... ; EXPLAIN EXECUTE query... to see if the plans are notably different.
EXPLAIN ANALYZE may give you more information, such as row count estimates and counts.
Usually people having this problem are trying to use prepared queries as a security measure to prevent SQL injection, rather than as a performance tuning option for expensive-to-plan queries frequently executed with a variety of different parameters. Those people should consider using client-side prepared statements if their client interface (eg PgJDBC) supports it.
At present, PostgreSQL does not offer a way to request re-planning of a prepared statement using a particular set of parameter values; doing so somewhat defeats the purpose of server-side prepared statements. Running a statistics check to see if a particular parameter value is notably outside the norm and automatically re-planning in that case has been discussed, but not agreed upon or implemented as yet.
See Using_EXPLAIN. If you're going to ask for help on the mailing lists, please read the Guide to reporting problems.
Why is my query much slower when run in a function than standalone?
See FAQ#Why is my query much slower when run as a prepared query?. Queries in PL/PgSQL functions are prepared and cached, so they execute in much the same way as if you'd
PREPAREd then
EXECUTEd the query yourself.
If you're having really severe issues with this that improving the table statistics or adjusting your query don't help with, you can work around it by forcing PL/PgSQL to re-prepare your query at every execution. To do this, use the
EXECUTE ... USING statement in PL/PgSQL to supply your query as a textual string. Alternately, the quote_literal or quote_nullable functions may be used to escape parameters substituted into query text.


text:
You can also check the configuration reference documentation.
Clustering/Session Replication HOW-TO
Important Note
Table of Contents
For the impatient
Simply add
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
to your
<Engine> or your
<Host> element to enable clustering.
Using the above configuration will enable all-to-all session replication
using the
DeltaManager to replicate session deltas. By all-to-all we mean that the session gets replicated to all the other
nodes in the cluster. This works great for smaller cluster but we don't recommend it for larger clusters(a lot of Tomcat nodes).
Also when using the delta manager it will replicate to all nodes, even nodes that don't have the application deployed.
To get around this problem, you'll want to use the BackupManager. This manager only replicates the session data to one backup node, and only to nodes that have the application deployed. Downside of the BackupManager: not quite as battle tested as the delta manager.
Here are some of the important default values:
- Multicast address is 188.8.131.52
- Multicast port is 45564 (the port and the address together determine cluster membership.
- The IP broadcasted is
java.net.InetAddress.getLocalHost().getHostAddress()(make sure you don't broadcast 127.0.0.1, this is a common error)
- The TCP port listening for replication messages is the first available server socket in range
- Listener is configured
- Two interceptors are configured
The following is the default cluster configuration:
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
<Manager className="org.apache.catalina.ha.session.DeltaManager"
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Membership className="org.apache.catalina.tribes.membership.McastService"
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor"/>
<Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
<Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>
<Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
Will cover this section in more detail later in this document.
The cluster implementation is written on the basis that a secure, trusted network is used for all of the cluster related network traffic. It is not safe to run a cluster on a insecure, untrusted network.
There are many options for providing a secure, trusted network for use by a Tomcat cluster. These include:
- private LAN
- a Virtual Private Network (VPN)
Cluster Basics
To run session replication in your Tomcat 8 container, the following steps should be completed:
- All your session attributes must implement
- Uncomment the
Clusterelement in server.xml
- If you have defined custom cluster valves, make sure you have the
ReplicationValvedefined as well under the Cluster element in server.xml
- If your Tomcat instances are running on the same machine, make sure the
Receiver.portattribute is unique for each instance, in most cases Tomcat is smart enough to resolve this on it's own by autodetecting available ports in the range 4000-4100
- Make sure your
web.xmlhas the
- If you are using mod_jk, make sure that jvmRoute attribute is set at your Engine
<Engine name="Catalina" jvmRoute="node01" >and that the jvmRoute attribute value matches your worker name in workers.properties
- Make sure that all nodes have the same time and sync with NTP service!
- Make sure that your loadbalancer is configured for sticky session mode.
Load balancing can be achieved through many techniques, as seen in the Load Balancing chapter.
Note: Remember that your session state is tracked by a cookie, so your URL must look the same from the out side otherwise, a new session will be created.
The Cluster module uses the Tomcat JULI logging framework, so you can configure logging
through the regular logging.properties file. To track messages, you can enable logging on the key:
To enable session replication in Tomcat, three different paths can be followed to achieve the exact same thing:
- Using session persistence, and saving the session to a shared file system (PersistenceManager + FileStore)
- Using session persistence, and saving the session to a shared database (PersistenceManager + JDBCStore)
- Using in-memory-replication, using the SimpleTcpCluster that ships with Tomcat (lib/catalina-tribes.jar + lib/catalina-ha.jar)
In this release of session replication, Tomcat can perform an all-to-all replication of session state using the
DeltaManager or
perform backup replication to only one node using the
The all-to-all replication is an algorithm that is only efficient when the clusters are small. For larger clusters, to use
a primary-secondary session replication where the session will only be stored at one backup server simply setup the BackupManager.
Currently you can use the domain worker attribute (mod_jk > 1.2.8) to build cluster partitions with the potential of having a more scalable cluster solution with the DeltaManager(you'll need to configure the domain interceptor for this). In order to keep the network traffic down in an all-to-all environment, you can split your cluster into smaller groups. This can be easily achieved by using different multicast addresses for the different groups. A very simple setup would look like this:
DNS Round Robin
Load Balancer
/ \
Cluster1 Cluster2
/ \ / \
Tomcat1 Tomcat2 Tomcat3 Tomcat4
What is important to mention here, is that session replication is only the beginning of clustering.
Another popular concept used to implement clusters is farming, i.e., you deploy your apps only to one
server, and the cluster will distribute the deployments across the entire cluster.
This is all capabilities that can go into with the FarmWarDeployer (s. cluster example at
In the next section will go deeper into how session replication works and how to configure it.
Cluster Information
Membership is established using multicast heartbeats.
Hence, if you wish to subdivide your clusters, you can do this by
changing the multicast IP address or port in the
<Membership> element.
The heartbeat contains the IP address of the Tomcat node and the TCP port that Tomcat listens to for replication traffic. All data communication happens over TCP.
ReplicationValve is used to find out when the request has been completed and initiate the
replication, if any. Data is only replicated if the session has changed (by calling setAttribute or removeAttribute
on the session).
One of the most important performance considerations is the synchronous versus asynchronous replication.
In a synchronous replication mode the request doesn't return until the replicated session has been
sent over the wire and reinstantiated on all the other cluster nodes.
Synchronous vs. asynchronous is configured using the
flag and is an integer value. The default value for the
SimpleTcpCluster/DeltaManager combo is
8, which is asynchronous. You can read more on the send flag(overview) or the
send flag(javadoc).
During async replication, the request is returned before the data has been replicated. async replication yields shorter
request times, and synchronous replication guarantees the session to be replicated before the request returns.
Bind session after crash to failover node
If you are using mod_jk and not using sticky sessions or for some reasons sticky session don't work, or you are simply failing over, the session id will need to be modified as it previously contained the worker id of the previous tomcat (as defined by jvmRoute in the Engine element). To solve this, we will use the JvmRouteBinderValve.
The JvmRouteBinderValve rewrites the session id to ensure that the next request will remain sticky (and not fall back to go to random nodes since the worker is no longer available) after a fail over. The valve rewrites the JSESSIONID value in the cookie with the same name. Not having this valve in place, will make it harder to ensure stickiness in case of a failure for the mod_jk module.
Remember, if you are adding your own valves in server.xml then the defaults are no longer valid, make sure that you add in all the appropriate valves as defined by the default.
With attribute sessionIdAttribute you can change the request attribute name that included the old session id. Default attribute name is org.apache.catalina.ha.session.JvmRouteOrignalSessionID.
You can enable this mod_jk turnover mode via JMX before you drop a node to all backup nodes! Set enable true on all JvmRouteBinderValve backups, disable worker at mod_jk and then drop node and restart it! Then enable mod_jk Worker and disable JvmRouteBinderValves again. This use case means that only requested session are migrated.
Configuration Example
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
<Manager className="org.apache.catalina.ha.session.BackupManager"
<Manager className="org.apache.catalina.ha.session.DeltaManager"
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Membership className="org.apache.catalina.tribes.membership.McastService"
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>
<Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
<Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
Break it down!!
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
The main element, inside this element all cluster details can be configured.
channelSendOptions is the flag that is attached to each message sent by the
SimpleTcpCluster class or any objects that are invoking the SimpleTcpCluster.send method.
The description of the send flags is available at
our javadoc site
DeltaManager sends information using the SimpleTcpCluster.send method, while the backup manager
sends it itself directly through the channel.
For more info, Please visit the reference documentation
<Manager className="org.apache.catalina.ha.session.BackupManager"
<Manager className="org.apache.catalina.ha.session.DeltaManager"
This is a template for the manager configuration that will be used if no manager is defined in the <Context>
element. In Tomcat 5.x each webapp marked distributable had to use the same manager, this is no longer the case
since Tomcat you can define a manager class for each webapp, so that you can mix managers in your cluster.
Obviously the managers on one node's application has to correspond with the same manager on the same application on the other node.
If no manager has been specified for the webapp, and the webapp is marked <distributable/> Tomcat will take this manager configuration
and create a manager instance cloning this configuration.
For more info, Please visit the reference documentation
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
The channel element is Tribes, the group communication framework
used inside Tomcat. This element encapsulates everything that has to do with communication and membership logic.
For more info, Please visit the reference documentation
<Membership className="org.apache.catalina.tribes.membership.McastService"
Membership is done using multicasting. Please note that Tribes also supports static memberships using the
StaticMembershipInterceptor if you want to extend your membership to points beyond multicasting.
The address attribute is the multicast address used and the port is the multicast port. These two together
create the cluster separation. If you want a QA cluster and a production cluster, the easiest config is to
have the QA cluster be on a separate multicast address/port combination than the production cluster.
The membership component broadcasts TCP address/port of itself to the other nodes so that communication between nodes can be done over TCP. Please note that the address being broadcasted is the one of the
Receiver.address attribute.
For more info, Please visit the reference documentation
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
In tribes the logic of sending and receiving data has been broken into two functional components. The Receiver, as the name suggests
is responsible for receiving messages. Since the Tribes stack is thread less, (a popular improvement now adopted by other frameworks as well),
there is a thread pool in this component that has a maxThreads and minThreads setting.
The address attribute is the host address that will be broadcasted by the membership component to the other nodes.
For more info, Please visit the reference documentation
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
The sender component, as the name indicates is responsible for sending messages to other nodes.
The sender has a shell component, the
ReplicationTransmitter but the real stuff done is done in the
sub component,
Tribes support having a pool of senders, so that messages can be sent in parallel and if using the NIO sender,
you can send messages concurrently as well.
Concurrently means one message to multiple senders at the same time and Parallel means multiple messages to multiple senders at the same time.
For more info, Please visit the reference documentation
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>
Tribes uses a stack to send messages through. Each element in the stack is called an interceptor, and works much like the valves do
in the Tomcat servlet container.
Using interceptors, logic can be broken into more manageable pieces of code. The interceptors configured above are:
TcpFailureDetector - verifies crashed members through TCP, if multicast packets get dropped, this interceptor protects against false positives, ie the node marked as crashed even though it still is alive and running.
MessageDispatchInterceptor - dispatches messages to a thread (thread pool) to send message asynchronously.
ThroughputInterceptor - prints out simple stats on message traffic.
Please note that the order of interceptors is important. The way they are defined in server.xml is the way they are represented in the channel stack. Think of it as a linked list, with the head being the first most interceptor and the tail the last.
For more info, Please visit the reference documentation
<Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
The cluster uses valves to track requests to web applications, we've mentioned the ReplicationValve and the JvmRouteBinderValve above.
The <Cluster> element itself is not part of the pipeline in Tomcat, instead the cluster adds the valve to its parent container.
If the <Cluster> elements is configured in the <Engine> element, the valves get added to the engine and so on.
For more info, Please visit the reference documentation
<Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
The default tomcat cluster supports farmed deployment, ie, the cluster can deploy and undeploy applications on the other nodes.
The state of this component is currently in flux but will be addressed soon. There was a change in the deployment algorithm
between Tomcat 5.0 and 5.5 and at that point, the logic of this component changed to where the deploy dir has to match the
webapps directory.
For more info, Please visit the reference documentation
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
Since the SimpleTcpCluster itself is a sender and receiver of the Channel object, components can register themselves as listeners to
the SimpleTcpCluster. The listener above
ClusterSessionListener listens for DeltaManager replication messages
and applies the deltas to the manager that in turn applies it to the session.
For more info, Please visit the reference documentation
Cluster Architecture
Component Levels:
| \
| --- Cluster --*
/ \
Cluster Context(1-N)
| \
| -- Manager
| \
| -- DeltaManager
| -- BackupManager
| \
Channel \
----------------------------- \
| \
Interceptor_1 .. \
| \
Interceptor_N \
----------------------------- \
| | | \
Receiver Sender Membership \
-- Valve
| \
| -- ReplicationValve
| -- JvmRouteBinderValve
-- LifecycleListener
-- ClusterListener
| \
| -- ClusterSessionListener
-- Deployer
-- FarmWarDeployer
How it Works
To make it easy to understand how clustering works, We are gonna take you through a series of scenarios.
In the scenario we only plan to use two tomcat instances
TomcatA and
We will cover the following sequence of events:
TomcatAstarts up
TomcatBstarts up (Wait that TomcatA start is complete)
TomcatAreceives a request, a session
S1is created.
TomcatBreceives a request for session
TomcatAstarts up
TomcatAreceives a request, invalidate is called on the session (
TomcatBreceives a request, for a new session (
TomcatAThe session
S2expires due to inactivity.
Ok, now that we have a good sequence, we will take you through exactly what happens in the session replication code
TomcatAstarts up
Tomcat starts up using the standard start up sequence. When the Host object is created, a cluster object is associated with it. When the contexts are parsed, if the distributable element is in place in web.xml Tomcat asks the Cluster class (in this case
SimpleTcpCluster) to create a manager for the replicated context. So with clustering enabled, distributable set in web.xml Tomcat will create a
DeltaManagerfor that context instead of a
StandardManager. The cluster class will start up a membership service (multicast) and a replication service (tcp unicast). More on the architecture further down in this document.
TomcatBstarts up
When TomcatB starts up, it follows the same sequence as TomcatA did with one exception. The cluster is started and will establish a membership (TomcatA,TomcatB). TomcatB will now request the session state from a server that already exists in the cluster, in this case TomcatA. TomcatA responds to the request, and before TomcatB starts listening for HTTP requests, the state has been transferred from TomcatA to TomcatB. In case TomcatA doesn't respond, TomcatB will time out after 60 seconds, and issue a log entry. The session state gets transferred for each web application that has distributable in its web.xml. Note: To use session replication efficiently, all your tomcat instances should be configured the same.
TomcatAreceives a request, a session
S1is created.
The request coming in to TomcatA is treated exactly the same way as without session replication. The action happens when the request is completed, the
ReplicationValvewill intercept the request before the response is returned to the user. At this point it finds that the session has been modified, and it uses TCP to replicate the session to TomcatB. Once the serialized data has been handed off to the operating systems TCP logic, the request returns to the user, back through the valve pipeline. For each request the entire session is replicated, this allows code that modifies attributes in the session without calling setAttribute or removeAttribute to be replicated. a useDirtyFlag configuration parameter can be used to optimize the number of times a session is replicated.
When TomcatA crashes, TomcatB receives a notification that TomcatA has dropped out of the cluster. TomcatB removes TomcatA from its membership list, and TomcatA will no longer be notified of any changes that occurs in TomcatB. The load balancer will redirect the requests from TomcatA to TomcatB and all the sessions are current.
TomcatBreceives a request for session
Nothing exciting, TomcatB will process the request as any other request.
TomcatAstarts up
Upon start up, before TomcatA starts taking new request and making itself available to it will follow the start up sequence described above 1) 2). It will join the cluster, contact TomcatB for the current state of all the sessions. And once it receives the session state, it finishes loading and opens its HTTP/mod_jk ports. So no requests will make it to TomcatA until it has received the session state from TomcatB.
TomcatAreceives a request, invalidate is called on the session (
The invalidate call is intercepted, and the session is queued with invalidated sessions. When the request is complete, instead of sending out the session that has changed, it sends out an "expire" message to TomcatB and TomcatB will invalidate the session as well.
TomcatBreceives a request, for a new session (
Same scenario as in step 3)
TomcatAThe session
S2expires due to inactivity.
The invalidate call is intercepted the same was as when a session is invalidated by the user, and the session is queued with invalidated sessions. At this point, the invalidated session will not be replicated across until another request comes through the system and checks the invalid queue.
Phuuuhh! :)
Membership Clustering membership is established using very simple multicast pings. Each Tomcat instance will periodically send out a multicast ping, in the ping message the instance will broad cast its IP and TCP listen port for replication. If an instance has not received such a ping within a given timeframe, the member is considered dead. Very simple, and very effective! Of course, you need to enable multicasting on your system.
TCP Replication Once a multicast ping has been received, the member is added to the cluster Upon the next replication request, the sending instance will use the host and port info and establish a TCP socket. Using this socket it sends over the serialized data. The reason I choose TCP sockets is because it has built in flow control and guaranteed delivery. So I know, when I send some data, it will make it there :)
Distributed locking and pages using frames Tomcat does not keep session instances in sync across the cluster. The implementation of such logic would be to much overhead and cause all kinds of problems. If your client accesses the same session simultaneously using multiple requests, then the last request will override the other sessions in the cluster.
Monitoring your Cluster with JMX
Monitoring is a very important question when you use a cluster. Some of the cluster objects are JMX MBeans
Add the following parameter to your startup script with Java 5:
set CATALINA_OPTS=\
-Dcom.sun.management.jmxremote \
-Dcom.sun.management.jmxremote.port=%my.jmx.port% \
-Dcom.sun.management.jmxremote.ssl=false \
List of Cluster Mbeans
|MBean ObjectName - Engine
|MBean ObjectName - Host
|The complete cluster element
|This manager control the sessions and handle session replication
type=Manager,context=${APP.CONTEXT.PATH}, host=${HOST}
type=Manager,context=${APP.CONTEXT.PATH}, host=${HOST}
|Manages the process of deploying an application to all nodes in the cluster
|Not supported
type=Cluster, host=${HOST}, component=deployer
|Represents a node in the cluster
|type=Cluster, component=member, name=${NODE_NAME}
type=Cluster, host=${HOST}, component=member, name=${NODE_NAME}
|This valve control the replication to the backup nodes
|This is a cluster fallback valve to change the Session ID to the current tomcat jvmroute.
Please see the clustering section of the FAQ.